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 install -D msw
yarn add -D msw
pnpm add -D msw
Import
import { http, HttpResponse } from 'msw';Quick Example
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
| Package | msw |
| Category | Testing |
| Weekly Downloads | 4M+ |
| License | MIT |
| Install | npm install -D msw |
Related Packages
Nock is an HTTP server mocking and expectations library for Node.js that intercepts outgoing HTTP re…
Jest is a delightful JavaScript testing framework with a focus on simplicity, created by Facebook. I…
Vitest is a blazing-fast unit testing framework powered by Vite, designed as a modern alternative to…
Testing Library is a family of packages that helps you test UI components in a way that resembles ho…
Sinon.js provides standalone test spies, stubs, and mocks for JavaScript that work with any test fra…
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.