API Reference

MSW

Mock Service Worker intercepts network requests in tests and the browser, enabling realistic API mocks without changing application code.

Official Documentation ↗
CompatibilityThis documentation covers version v3.0.3. Check the official docs for the latest API surface.

Installation

npmnpm install -D msw
pnpmpnpm add -D msw
yarnyarn add -D msw

Methods

Mock Service Worker intercepts HTTP requests at the network boundary. In Node tests it uses a request interceptor; in the browser it uses a Service Worker. The application keeps using fetch, so the test exercises the real client code instead of a mocked module.

Lifecycle

Create one server with base handlers, start it before the suite, reset handlers after each test, and close it after the suite. Per-test handlers can override a base handler for one case. Without a reset, a test can depend on a handler defined by an earlier test.

Simulate failure, not only success

Return 4xx and 5xx responses, malformed JSON, and delayed responses. Assert loading, error, empty, and retry states. A suite that only mocks 200 responses does not test the code that users hit during an incident.

Keep handlers honest

Handlers should mirror the real API contract. When the contract changes, update the handlers and the contract test together. A mock that drifts from the server creates false confidence; use contract tests or schema validation for the boundary.

FAQ

Does MSW patch fetch or the network layer?
MSW intercepts at the network boundary using a Service Worker in the browser and a request interceptor in Node. Application code continues to use fetch or its normal client.
Why do my tests leak handlers between cases?
Call resetHandlers after each test and close the server after the suite. A shared server with per-test overrides should always reset to the base handlers.
Can MSW simulate network errors and delays?
Yes. Return a 5xx Response, throw a network error, or use a delay before responding. Assert the loading, error, and retry states, not only the success path.