Mock HTTP requests with setupWorker, setupServer, http.get/post handlers, HttpResponse factory, passthrough(), and runtime handler overrides
0 / 5 completed
1 / 5
What is the difference between setupWorker and setupServer in MSW?
setupWorker vs setupServer:setupWorker(...handlers).start() in browser code — the Service Worker intercepts real fetch/XHR calls. setupServer(...handlers) in Node.js (Jest/Vitest/Playwright) — MSW patches the http module. Both accept the same http.get(), http.post(), and graphql.* handler arrays, making it easy to share handlers between browser and test environments.
2 / 5
How does http.get() define a request handler in MSW v2?
MSW http.get(): Example: http.get('/api/user/:id', ({ params }) => { return HttpResponse.json({ id: params.id, name: 'Alice' }) }). URL patterns support path parameters and wildcards. The handler returns an HttpResponse which MSW delivers to the calling code as if it were a real network response. Handlers are tried in declaration order.
3 / 5
What does HttpResponse provide in MSW v2?
HttpResponse:HttpResponse.json({ data: [] }, { status: 200 }) sets Content-Type: application/json automatically. HttpResponse.text('ok'), HttpResponse.error() (network error, not HTTP error). MSW v2 replaced returning plain Response with HttpResponse for better default header handling and a more ergonomic API.
4 / 5
What does passthrough() do in an MSW handler?
passthrough(): Return passthrough() from a handler to let the request go to the real network. Example: http.get('https://api.example.com/public/*', () => passthrough()) — public endpoints hit the real server while authenticated endpoints are mocked. Import from msw: import { passthrough } from 'msw'.
5 / 5
How do you override handlers at runtime in MSW during tests?
server.use() override: Common pattern: beforeAll(() => server.listen()), afterEach(() => server.resetHandlers()), afterAll(() => server.close()). Inside a test: server.use(http.get('/api/user', () => HttpResponse.json({ error: 'not found' }, { status: 404 }))). resetHandlers() removes these overrides, restoring the baseline handlers for the next test.