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.
Mock Service Worker (MSW) is a client-side API mocking library that intercepts outgoing requests using Service Workers.
Features
- Server-less. Mocking that doesn't establish any servers, operating entirely in a browser;
- Seamless. Forget about stubs and hacks that make your code smell. Leverage a dedicated layer of interception to keep your code clean and shiny.
- Deviation-free. Request the same resources you would in production, and mock their responses. No more conditional URLs, no more mock-specific parts of code in your app.
- 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 start
Install the library in your application:
$ npm install msw --save-dev
Now we have to copy the Service Worker file that's responsible for requests interception. To do so, run the following command in your project's root directory:
$ npx msw init <PUBLIC_DIR>
Provide the path to your public directory instead of the <PUBLIC_DIR>
placeholder above. Your public directory is usually a directory being served by a server (i.e. ./public
or ./dist
). Running this command will place the mockServiceWorker.js
file into given directory.
For example, in Create React App you would run: npx msw init ./public
Once the Service Worker has been copied, we can continue with creating a mocking definition file. For the purpose of this short tutorial we are going to keep all our mocking logic in the mocks.js
file, but the end file structure is up to you.
$ touch mock.js
Open that file and follow the example below to create your first mocking definition:
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. You can import the mocking definition file conditionally, so it's never loaded on production:
if (process.env.NODE_ENV === 'development') {
require('./mocks')
}
Verify the MSW is running by seeing a successful Service Worker activation message in the browser's console. Now any outgoing request of your application are intercepted by the Service Worker, signaled to the client-side library, and matched against the mocking definition. If a request matches any definition, its response is being mocked and returned to the browser.
![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.
We have prepared a set of step-by-step tutorials to get you started with mocking the API type you need. For example, did you know you can mock a GraphQL API using MSW? Find detailed instructions in the respective tutorials below.
Tutorials
Examples