ReactMedium

Mocking APIs in tests?

Mock APIs at the network level with Mock Service Worker (MSW): define request handlers once, and they intercept fetch and XHR calls in Node.js tests (Vitest, Jest) and in the browser (Storybook, development). Your components keep using real fetch, Axios or TanStack Query, so tests exercise the real data layer while staying fast and deterministic.

Why MSW over module mocks

  • No need to mock fetch, Axios or your API client module; tests are independent of how requests are made.
  • The same handlers work in tests, Storybook and local development.
  • Realistic: status codes, headers, delays, errors and streaming responses.

Setup (MSW 2)

  1. Handlers: http.get("/api/user", () => HttpResponse.json({ name: "Ada" })).
  2. Node: setupServer(...handlers) with server.listen() in beforeAll, server.resetHandlers() in afterEach, server.close() in afterAll.
  3. Per-test overrides: server.use(http.get("/api/user", () => new HttpResponse(null, { status: 500 }))) to test error states.
  4. Browser: setupWorker(...handlers).start() for development and Storybook.

Other options

  • Module mocks (vi.mock("./api")): quick for unit tests of components that receive data via a service, but tie tests to implementation.
  • Fake fetch (vi.spyOn(globalThis, "fetch")): fine for a single call; awkward at scale.
  • Contract tests / generated mocks from OpenAPI specs to keep mocks in sync with the real API.

Tips

  • Use onUnhandledRequest: "error" to catch requests you forgot to mock.
  • Reset TanStack Query caches between tests and disable retries to keep error tests fast.
  • Simulate slow responses with delay() to test loading states.

Code example

tsx
1// test/handlers.ts
2import { http, HttpResponse, delay } from "msw";
3
4export const handlers = [
5 http.get("/api/user/:id", async ({ params }) => {
6 await delay(50);
7 return HttpResponse.json({ id: params.id, name: "Ada Lovelace" });
8 }),
9 http.post("/api/comments", async ({ request }) => {
10 const body = (await request.json()) as { text: string };
11 return HttpResponse.json({ id: "c1", text: body.text }, { status: 201 });
12 }),
13];
14
15// test/setup.ts
16import { setupServer } from "msw/node";
17export const server = setupServer(...handlers);
18beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
19afterEach(() => server.resetHandlers());
20afterAll(() => server.close());
21
22// user-card.test.tsx - override a handler to test the error state
23// test("shows an error", async () => {
24// server.use(http.get("/api/user/:id", () => new HttpResponse(null, { status: 500 })));
25// render(<UserCard id="1" />);
26// expect(await screen.findByRole("alert")).toHaveTextContent(/couldn't load/i);
27// });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app