Features
- Intercepts requests at the network level (Service Worker)
- Works in browser and Node.js environments
- Request handlers reusable across tests, dev, and demos
- Type-safe REST and GraphQL request matching
Pros
- Tests use real fetch/axios code, not mocked modules
- Same handlers work in tests, Storybook, and development
- Framework-agnostic, works with any HTTP client
Cons
- Service Worker setup required for browser mocking
- Learning curve for handler composition patterns
- Debugging intercepted requests can be non-obvious
Overview
MSW (Mock Service Worker) is an API mocking library that intercepts HTTP requests at the network level. Unlike traditional mocking approaches that replace fetch or axios with mock implementations, MSW uses a Service Worker in the browser and request interception in Node.js to catch real network requests and return mock responses.
This approach means your application code makes real HTTP requests, and MSW intercepts them transparently. Your tests exercise the actual network layer of your application, catching issues that module-level mocks would miss.
A key benefit is handler reusability: the same request handlers you write for testing can be used in Storybook stories, during local development (when a backend is unavailable), and in demos. This eliminates the need to maintain separate mocking strategies for different contexts.
When to Use
Use MSW when testing components or applications that make HTTP requests. It is the best approach for API mocking because it tests your actual network code without requiring backend services to be running.
Getting Started
npm install --save-dev msw
npx msw init public/ --save
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(
http.get('/api/user', () => HttpResponse.json({ name: 'John' }))
)
beforeAll(() => server.listen())
afterAll(() => server.close())