msw
Installation
SKILL.md
MSW (Mock Service Worker)
Overview
MSW intercepts network requests at the service worker level (browser) or in-memory (Node.js) to mock REST and GraphQL APIs for tests and local development. It uses the same handlers for both environments, keeping mocks consistent, and works transparently with any HTTP client (fetch, axios, Apollo) without modifying application code.
Instructions
- When setting up handlers, define REST handlers with
http.get(),http.post(), etc. and GraphQL handlers withgraphql.query()andgraphql.mutation(), returning responses viaHttpResponse.json(). - When testing in Node.js, use
setupServer(...handlers)withserver.listen()before tests,server.resetHandlers()between tests, andserver.close()after all tests. - When developing in the browser, use
setupWorker(...handlers)and runnpx msw init ./publicto generate the service worker file, which intercepts requests visible in DevTools. - When overriding per test, use
server.use()to add temporary handlers for error states or edge cases, which scope to the current test and reset afterward. - When simulating network issues, use
delay(ms)for latency,HttpResponse.error()for failures, and custom status codes for error responses. - When organizing handlers, keep shared handlers in
src/mocks/handlers.tsfor reuse across test files and the dev server, with per-test overrides viaserver.use().