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 name | Description |
---|---|
request | Information about the captured request. |
response | Function to create the mocked response. |
context | Context 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.js2import { setupWorker, rest } from 'msw'34const worker = setupWorker(5 rest.get(6 '/user',7 // Example of a response resolver that returns8 // 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)1920worker.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.js2export const mockUser = (req, res, ctx) => {3 return res(4 ctx.json({5 firstName: 'John',6 age: 38,7 }),8 )9}
1// src/mocks/index.js2import { setupWorker, rest } from 'msw'3import { mockUser } from './resolvers/mockUser'45const worker = setupWorker(6 rest.get('/user', mockUser),7 rest.get('/me', mockUser),8)910worker.start()
Conditional response
When a response resolver returns the req.passthrough
call, MSW will perform the captured request as-is, hitting the actual endpoint and returning its 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')34 if (userId === 'abc-123') {5 // Return a mocked response only if the `userId` query parameter6 // equals to a specific value.7 return res(8 ctx.json({9 firstName: 'John',10 lastName: 'Maverick',11 }),12 )13 }1415 // Otherwise, explicitly state that you wish to perform this request as-is.16 return req.passthrough()17})
Alternatively, you can use an explicit return
statement without the res()
call to achieve the same behavior.
1rest.post('/login', async (req, res, ctx) => {2 const { username } = await req.json()34 if (username === 'real-user') {5 // Bypass this request, returning an actual response6 // only when the `username` equals to a specific value.7 return req.passthrough()8 }910 // Otherwise, always respond with a mocked response.11 return res(12 ctx.json({13 id: 'abc-123',14 }),15 )16})