Mocking Fetch request in Testing Library

Published on 2024-08-29 · Programming JavaScript TypeScript React Testing Library Testing

Let’s say you use your own wrapper on native Fetch API, that adds necessary headers, parses data into the body, and crucially handles response, whether it’s application/json or some file to parse.

I run into some issues when I was trying to mock that kind of scenario, at first I just mocked plain response, but was quickly stopped by a condition that uses response.text(). Finally I found solution for all my cases:

// test.spec.ts
import { vi } from "vitest";

describe("test", () => {
    const headers = new Headers();
    headers.append("content-type", "application/json");

    const responseBody: Array<Record<string, string>> = [{ test: "value" }];
    const response = {
        ok: true,
        statusText: "OK",
        status: 200,
        json: async () => responseBody,
        headers,
    } as Response;

    beforeEach(() => {
        vi.clearAllMocks();
    });

    it("test case", async () => {
        globalThis.fetch = vi.fn().mockResolvedValue(response);

        // ... rest of the test case
    });
});