mswMock Service Worker

use()

Prepends given request handlers to the current server instance.

Request handler added after the initial setupServer call is referred to as runtime request handler. When added, it affects network communication as any other request handler.

Examples

Runtime request handler

1import { rest } from 'msw'
2import { setupServer } from 'msw/node'
3
4const server = setupServer(
5 // Request handlers given to the `setupServer` call
6 // are referred to as initial request handlers.
7 rest.get('/book/:bookId', (req, res, ctx) => {
8 return res(ctx.json({ title: 'Lord of the Rings' }))
9 }),
10)
11
12test('supports sign in user flow', () => {
13 // Adds the "POST /login" request handler as a part of this test.
14 server.use(
15 rest.post('/login', (req, res, ctx) => {
16 return res(ctx.json({ success: true }))
17 }),
18 )
19})

Permanent override

When a runtime request handler overlaps with an existing one (has the same predicate), the runtime handler always takes priority. Leverage this to provision API behavior overrides per test suite.

1import { rest } from 'msw'
2import { setupServer } from 'msw/node'
3
4const server = setupServer(
5 // Initial request handler for a book detail.
6 rest.get('/book/:bookId', (req, res, ctx) => {
7 return res(ctx.json({ title: 'Lord of the Rings' }))
8 }),
9)
10
11test('handles server error gracefully', () => {
12 server.use(
13 // Runtime request handler override for the "GET /book/:bookId".
14 rest.get('/book/:bookId', (req, res, ctx) => {
15 return res(ctx.json({ title: 'A Game of Thrones' }))
16 }),
17 )
18
19 // Any requests to "GET /book/:bookId" will return
20 // the "A Game of Thrones" mocked response from
21 // the runtime request handler override.
22})

One-time override

Request handler override can be used to handle only the next matching request. After a one-time request handler has been used, it never affects the network again.

Note that restoring the handlers via .restoreHandlers() can re-activate one-time request handlers.

To declare a one-time request handler override make sure your handler responds using res.once().

1const server = setupServer(
2 // Initial request handler for a book detail.
3 rest.get('/book/:bookId', (req, res, ctx) => {
4 return res(ctx.json({ title: 'Lord of the Rings' }))
5 }),
6)
7
8test('handles server error gracefully', () => {
9 server.use(
10 rest.get('/book/:bookId', (req, res, ctx) => {
11 // The first matching "GET /book/:bookId" request
12 // will receive this mocked response.
13 return res.once(
14 ctx.status(500),
15 ctx.json({ message: 'Internal server error' }),
16 )
17 }),
18 )
19
20 // Request to "GET /book/:bookId" in this test will return
21 // a mocked error response (500).
22})
23
24test('renders a book detail', () => {
25 // Request to "GET /book/:bookId" in this test will return
26 // a mocked "Lord of the Rings" book detail.
27})