MSW for Realistic API Mocking
What you'll learn: How to use Mock Service Worker to intercept network requests at the network level, creating more realistic and maintainable API mocks than direct fetch mocking.
Why Network-Level Mocking Matters
When you mock fetch directly (like vi.mock('fetch')), you're replacing the actual API call mechanism with a fake. This works, but it creates tests that know too much about how your code makes requests. If you switch from fetch to axios, your mocks break.
MSW takes a different approach: it intercepts requests at the network boundary using a service worker. Your component still calls the real fetch, makes real HTTP requests, and processes real responses—MSW just catches those requests before they leave the browser and returns your test data.
The Realistic Testing Advantage
Think of MSW like a stunt double for your API server. Your code performs all the same actions (sending headers, parsing JSON, handling errors), but the "server" responding is controlled by your test.
This means:
- Your fetch logic runs for real (no implementation detail mocking)
- Tests survive refactoring from fetch to axios to a custom hook
- Request/response handling is actually tested (serialization, headers, error parsing)
- The same handlers work in tests AND dev mode (you already configured this)
// Your component uses real fetch
await fetch('/api/users')
// MSW intercepts it at network level
// → Component never knows it's a mock
// → All your real request code executes
// → Response handling is genuinely tested
Key Takeaway: MSW intercepts network requests at the boundary layer, allowing your real request code to execute while giving you full control over responses—this tests more realistically than mocking fetch directly while remaining decoupled from implementation details.