Skip to the page

Testing React components · mid

Mocking the network with MSW

Mock Service Worker intercepts real HTTP requests (with a service worker in the browser and request interceptors in Node), so your components use their real fetch/axios/React Query code while tests decide the responses, including errors, delays and races.

The notes

What you must know

  • Handlers: http.get('/api/products/:id', ({ params }) => HttpResponse.json({ id: params.id })). GraphQL and WebSocket handlers exist too.
  • Node tests: const server = setupServer(...handlers); beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => server.resetHandlers()); afterAll(() => server.close()).
  • Per-test overrides: server.use(http.get(..., () => new HttpResponse(null, { status: 500 }))) to test the error UI; resetHandlers removes them after the test.
  • Simulate slowness and races with await delay(ms) in a handler; simulate network failure with HttpResponse.error().
  • The same handlers work in the browser (setupWorker) for local development and Storybook, so mocks stay in one place.
  • Why not mock fetch directly: you skip your real request code (headers, URL building, parsing, retries) and tie tests to one HTTP client.

The red pen

Common traps: mistake → fix

  • Mistake: "Mock axios/fetch with jest.mock"

    Fix: the test no longer checks your request code or the HTTP client config.

  • Mistake: "Unhandled requests are fine"

    Fix: they hide missing mocks or real calls; set onUnhandledRequest: 'error'.

  • Mistake: "Handlers from one test don't affect others"

    Fix: server.use overrides stay until resetHandlers runs.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you mock APIs in component tests?
  2. MSW vs mocking fetch: trade-offs?
  3. How do you test the error state and the loading state?
  4. How would you test that out-of-order responses don't show stale results?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview