Mock Service Worker
  1. Basics
  2. Response resolver

Response resolver

Response resolver is a function that accepts a captured request and may return a mocked response.

Parameters

Response resolver function accepts the following parameters:

Parameter nameDescription
requestInformation about the captured request.
responseFunction to create the mocked response.
contextContext utilities specific to the current request handler.

Examples

Basic

The most common usage is when a response resolver is used as an argument to a request handler to specify a mocked response it should return.

1// src/mocks.js
2import { setupWorker, rest } from 'msw'
3
4const worker = setupWorker(
5 rest.get(
6 '/user',
7 // Example of a response resolver that returns
8 // a "Content-Type: application/json" response.
9 (req, res, ctx) => {
10 return res(
11 ctx.json({
12 firstName: 'John',
13 age: 38,
14 }),
15 )
16 },
17 ),
18)
19
20worker.start()

Reusable resolver

Since response resolver is a regular function, you can declare and reuse it across multiple request handlers.

1// src/mocks/resolvers/mockUser.js
2export const mockUser = (req, res, ctx) => {
3 return res(
4 ctx.json({
5 firstName: 'John',
6 age: 38,
7 }),
8 )
9}
1// src/mocks/index.js
2import { setupWorker, rest } from 'msw'
3import { mockUser } from './resolvers/mockUser'
4
5const worker = setupWorker(
6 rest.get('/user', mockUser),
7 rest.get('/me', mockUser),
8)
9
10worker.start()

Conditional response

When nothing is returned from a response resolver, MSW performed a captured request as-is, hitting the actual endpoint returning the response. Leverage this behavior to perform conditional mocking, for example based on the request's payload.

1rest.get('/user', (req, res, ctx) => {
2 const userId = req.url.searchParams.get('userId')
3
4 if (userId === 'abc-123') {
5 // Return a mocked response only if the `userId` query parameter
6 // equals to a specific value.
7 return res(
8 ctx.json({
9 firstName: 'John',
10 lastName: 'Maverick',
11 }),
12 )
13 }
14
15 // No return statement, perform the request as-is.
16})

Alternatively, you can use an explicit return statement without the res() call to achieve the same behavior.

1rest.post('/login', (req, res, ctx) => {
2 const { username } = req.body
3
4 if (username === 'real-user') {
5 // Bypass this request, returning an actual response
6 // only when the `username` equals to a specific value.
7 return
8 }
9
10 // Otherwise, always respond with a mocked response.
11 return res(
12 ctx.json({
13 id: 'abc-123',
14 }),
15 )
16})