Mock Service Worker
Problem
Traditional API mocking requires duplicating mock logic between tests and development, tightly coupling tests to implementation details. Mocks that stub at the function level miss entire layers of the network stack, failing to catch serialization bugs, CORS issues, or incorrect request headers.
Solution
Intercept network requests at the service worker level to mock API responses during development and testing. This provides realistic mocking that works across all request libraries.
Example
This example shows how to set up MSW to intercept API requests in tests, returning mock data without modifying application code or using real backend services.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
// Define mock handlers for API endpoints
const server = setupServer(
// Intercept GET requests to /api/user
rest.get('/api/user', (req, res, ctx) => {
// Return mock JSON response
return res(ctx.json({ name: 'John' }));
})
);
// Start intercepting requests before tests run
beforeAll(() => server.listen());
// Clean up after all tests complete
afterAll(() => server.close());
Benefits
- Provides realistic mocking by intercepting actual network requests.
- Works with any request library without modifying application code.
- Catches bugs in serialization, headers, and request configuration.
- Enables development without backend dependencies or flaky test environments.
Tradeoffs
- Requires service worker setup which adds configuration complexity.
- Can be confusing when debugging since requests are intercepted invisibly.
- May not catch all integration issues that occur with real backend.
- Needs maintenance when API contracts change or evolve.