What is msw?
The msw (Mock Service Worker) npm package is a tool for mocking network requests at the service worker level. It allows developers to intercept and modify any outgoing HTTP requests from their application, which is useful for testing, development, and debugging purposes. It can be used in both browser and Node.js environments.
What are msw's main functionalities?
Mocking REST API requests
This feature allows you to intercept and mock responses to REST API requests. The code sample demonstrates how to set up a mock server that responds to a GET request to '/user' with a JSON object containing a username.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/user', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ username: 'admin' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Mocking GraphQL API requests
This feature enables the mocking of GraphQL API requests. The code sample shows how to create a mock server that handles a GraphQL query named 'GetUser' and returns a response with user data.
import { graphql } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
graphql.query('GetUser', (req, res, ctx) => {
return res(ctx.data({ user: { id: '1', name: 'John Doe' } }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Delaying mocked responses
This feature allows you to simulate network delays in your mocked responses. The code sample sets up a mock server that delays the response to a GET request to '/user' by 1500 milliseconds.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/user', (req, res, ctx) => {
return res(ctx.delay(1500), ctx.json({ username: 'admin' }));
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Other packages similar to msw
nock
Nock is a popular HTTP server mocking and expectations library for Node.js. It allows you to intercept HTTP requests and provide predefined responses. Unlike msw, which works with service workers and can be used in both browser and Node.js environments, nock is designed specifically for Node.js.
axios-mock-adapter
axios-mock-adapter is a library for mocking Axios requests. It provides a way to mock requests made using the Axios library, allowing you to specify the expected response for a given request. This package is more specific to Axios, while msw is agnostic to the HTTP client used.
jest-fetch-mock
jest-fetch-mock is a package that provides a way to easily mock fetch requests when using Jest. It's specifically tailored for Jest users and is used to mock the global fetch function. msw, on the other hand, intercepts requests at a lower level and is not limited to Jest or fetch.
MSW
Mock Service Worker (MSW) is a client-side API mocking library that operates by intercepting outgoing requests using Service Workers.
Features
- Server-less. Doesn't establish any servers, operating entirely in a browser;
- Deviation-free. Intercepts production URI requests from your page and mocks their responses, without having to deal with mocked URI.
- Mocking as a tool. Enable/change/disable mocking on runtime instantly without any compilations or rebuilds. Control the MSW lifecycle from your browser's DevTools;
- Essentials. Use Express-like syntax to define which requests to mock. Respond with custom status codes, headers, delays, or create custom response resolvers.
"This is awesome."
– Kent C. Dodds
Documentation
Quick look
$ npm install msw --save-dev
Now we have to put the mockServiceWorker.js
file in your public directory. That is usually a directory being served by your server (i.e. public/
or dist/
). The placing of the file is done by running the following command from your project's root directory:
$ npx msw init <PUBLIC_DIR>
For example, in a Create React App you would have to run: npx msw init public/
.
MSW workflow consist of three phases:
import { composeMocks, rest } from 'msw'
const { start } = composeMocks(
rest.get('https://github.com/octocat', (req, res, ctx) => {
return res(
ctx.delay(1500),
ctx.status(202, 'Mocked status'),
ctx.json({
message: 'This is a mocked error',
}),
)
}),
)
start()
Import the mocks.js
module into your application to enable the mocking.
import './mocks'
Once enabled, any requests matching the defined paths will be intercepted by Service Worker, which would respond with mocked responses.
![Chrome DevTools Network screenshot with the request mocked](https://github.com/open-draft/msw/blob/master/media/msw-quick-look-network.png?raw=true)
Notice the 202 Mocked status (from ServiceWorker)
status in the response.
There is a set of step-by-step tutorials to get you started with mocking the API type you need. Please refer to those tutorials below for more detailed instructions.
Tutorials
Examples