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.
Motivation
Problems of traditional mocking:
- Often relies on a mocking server which you need to run and maintain;
- Doesn't really mock requests, rather replaces their urls to point to a mocking server, instead of a production server;
- Brings extra dependencies to your application, instead of being a dependency-free development tool;
Benefits of msw
:
- Serverless. Doesn't establish any mocking servers whatsoever;
- Deviation-free. Request the same resources as you would in production, let the library handle response mocking of those that match your defined routes;
- A tool. Mocking is a development process, thus enable/disable it at any point, change the routes without any rebuilds, control the lifecycle from your browser's DevTools;
Getting started
Install
npm install msw --save-dev
Use
import { msw } from 'msw'
msw.get(
'https://api.github.com/repo/:repoName',
(req, res, { status, set, delay, json }) => {
const { repoName } = req.params
return res(
status(403),
set({ 'Custom-Header': 'foo' }),
delay(1000),
json({ errorMessage: `Repository "${repoName}" not found` }),
)
)
msw.start()
Import your mocks.js
module anywhere in your application to enable the mocking:
import './mocks.js'
How does this work?
The library spawns a ServiceWorker that notifies the library about any outgoing requests from your application. A request is than matched against the mocking routes you have defined, and is mocked with the first match.
Browser support
Please note that this library is meant to be used for development only. It doesn't require nor encourage you to install any ServiceWorker on the production environment.
See browser support for ServiceWorkers