🧪
Testing4M+/wkMIT

msw

Mock Service Worker (MSW) is an API mocking library that uses the Service Worker API to intercept requests on the network level, providing seamless mocking for

Installation

npm
npm install -D msw
yarn
yarn add -D msw
pnpm
pnpm add -D msw

Import

ESM
import { http, HttpResponse } from 'msw';

Quick Example

usage
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';

const server = setupServer(
  http.get('/api/users', () => {
    return HttpResponse.json([
      { id: 1, name: 'John' },
    ]);
  }),
);

server.listen();

About msw

Mock Service Worker (MSW) is an API mocking library that uses the Service Worker API to intercept requests on the network level, providing seamless mocking for both browser and Node.js environments. Unlike Nock which patches Node.js internals, MSW uses a Service Worker in the browser to intercept fetch and XMLHttpRequest calls without modifying application code or HTTP client configuration, meaning your application code makes real HTTP requests that get intercepted transparently. In Node.js, MSW patches the request-issuing modules at the appropriate level. MSW supports both REST and GraphQL API mocking with an intuitive handler syntax: http.get('/api/users', () => HttpResponse.json([...])). Handlers can inspect request parameters, headers, cookies, and bodies to return dynamic responses. MSW encourages a single source of mock definitions shared between development, testing, and Storybook stories, reducing duplication and ensuring consistency. The library supports response streaming, network error simulation, request passthrough, and runtime request observation. MSW has become the recommended mocking approach for Testing Library and is increasingly preferred over Nock and Sinon for its transparent interception model.

Quick Facts

Packagemsw
CategoryTesting
Weekly Downloads4M+
LicenseMIT
Installnpm install -D msw

Related Packages

Browse npm Packages by Category

Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.