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:
- Realistic: Your component makes a real network request.
- Reuse: The same mocks can be used for development, unit tests, and E2E tests.
- Resilient: If you switch from
fetchtoaxios, your tests won't break because the network layer is what's being mocked.
💻 Code Example
code
1// mocks/handlers.ts2import { http, HttpResponse } from 'msw'34export const handlers = [5 http.get('https://api.example.com/user', () => {6 return HttpResponse.json({ name: 'Test User' })7 }),8]910// UserProfile.test.tsx11import { render, screen } from '@testing-library/react'12import UserProfile from './UserProfile'1314test('loads and displays user data', async () => {15 render(<UserProfile />)1617 // Use findBy to wait for the async MSW response18 const userName = await screen.findByText('Test User')19 expect(userName).toBeInTheDocument()20})
🏋️ Practice Exercise
- Set up MSW in a project and mock a GET request.
- Write a test for a 'Failure' scenario (e.g., the API returns a 500 error) and ensure your component shows an error message.
- Mock a POST request (like a form submission) and verify that the correct payload was sent.
- 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()andserver.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
Was this topic helpful?