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)
- Handlers:
http.get("/api/user", () => HttpResponse.json({ name: "Ada" })). - Node:
setupServer(...handlers)withserver.listen()inbeforeAll,server.resetHandlers()inafterEach,server.close()inafterAll. - Per-test overrides:
server.use(http.get("/api/user", () => new HttpResponse(null, { status: 500 })))to test error states. - 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.ts2import { http, HttpResponse, delay } from "msw";34export 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];1415// test/setup.ts16import { setupServer } from "msw/node";17export const server = setupServer(...handlers);18beforeAll(() => server.listen({ onUnhandledRequest: "error" }));19afterEach(() => server.resetHandlers());20afterAll(() => server.close());2122// user-card.test.tsx - override a handler to test the error state23// 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.