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 with graphql.query() and graphql.mutation(), returning responses via HttpResponse.json().
  • When testing in Node.js, use setupServer(...handlers) with server.listen() before tests, server.resetHandlers() between tests, and server.close() after all tests.
  • When developing in the browser, use setupWorker(...handlers) and run npx msw init ./public to 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.ts for reuse across test files and the dev server, with per-test overrides via server.use().

Examples

Example 1: Mock a REST API for component tests

Installs
3
GitHub Stars
157
First Seen
1 day ago
msw — terminalskills/skills