Mocking APIs with MSW

0/2 in this phase0/36 across the roadmap

📖 Concept

You shouldn't hit real APIs in your unit tests. It makes tests slow, flaky, and dependent on a network connection.

Mock Service Worker (MSW) is the modern gold standard for mocking. Instead of mocking the fetch function itself, MSW intercepts the network requests at the browser/node level and returns your mock data.

Why MSW is better:

  1. Realistic: Your component makes a real network request.
  2. Reuse: The same mocks can be used for development, unit tests, and E2E tests.
  3. Resilient: If you switch from fetch to axios, your tests won't break because the network layer is what's being mocked.

💻 Code Example

codeTap to expand ⛶
1// mocks/handlers.ts
2import { http, HttpResponse } from 'msw'
3
4export const handlers = [
5 http.get('https://api.example.com/user', () => {
6 return HttpResponse.json({ name: 'Test User' })
7 }),
8]
9
10// UserProfile.test.tsx
11import { render, screen } from '@testing-library/react'
12import UserProfile from './UserProfile'
13
14test('loads and displays user data', async () => {
15 render(<UserProfile />)
16
17 // Use findBy to wait for the async MSW response
18 const userName = await screen.findByText('Test User')
19 expect(userName).toBeInTheDocument()
20})

🏋️ Practice Exercise

  1. Set up MSW in a project and mock a GET request.
  2. Write a test for a 'Failure' scenario (e.g., the API returns a 500 error) and ensure your component shows an error message.
  3. Mock a POST request (like a form submission) and verify that the correct payload was sent.
  4. Integrate MSW with 'TanStack Query' and see how it simplifies testing data-heavy components.

⚠️ Common Mistakes

  • Mocking at the component level (like mocking the hook) instead of the network level.

  • Forgetting to call server.listen() and server.close() in your test setup.

  • Hardcoding full URLs in mocks that change between environments.

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Mocking APIs with MSW