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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- How do you mock APIs in component tests?
- MSW vs mocking fetch: trade-offs?
- How do you test the error state and the loading state?
- How would you test that out-of-order responses don't show stale results?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.