response
Response (res
) is a function that composes a mocked response object.
Unlike the Response
object in NodeJS, the res
argument in Mock Service Worker is used to create and transform a mocked response. When called, it passes a created response from one response transformer to another, eventually resolving to a mocked response used by the Service Worker.
Mocked response
A call to the res()
function creates a mocked response object. Each response transformer accepted by the res()
function modifies that mocked response and passes it to the next response transformer, thus, creating a functional composition.
Properties
Property name | Type | Description |
---|---|---|
status | number | Mocked response HTTP status code. (Default: 200 ) |
statusText | string | HTTP status text of the current status code. |
body | string | Stringified body of the response. |
headers | Headers | Mocked response HTTP headers. |
delay | number | Delay duration (ms) before responding with a mocked response. |
Example
Standard usage
1rest.get('/users', (req, res, ctx) => {2 return res(3 // This response transformer sets a custom status text on the response.4 ctx.status(301),5 // While this one appends a "Content-Type" response header.6 ctx.set('Content-Type', 'application/json'),7 )8})
Raw usage
The res()
call can accept a function that modifies and returns a created mocked response instance. It's recommended, however, to use standard response transformers for faster reference and reliability.
1rest.get('/users', (req, res) => {2 return res((res) => {3 res.status = 3014 res.headers.set('Content-Type', 'application/json')5 return res6 })7})
Custom response composition
Usually the res
function is available as an argument of a request handler. However, in some cases (like building a custom response composition) it's useful to import the res
function directly, outside of the request handler's scope.
You can do that by importing the response
function from the msw
package:
1// src/mocks/res.js2import { response, context } from 'msw'34export function res(...transformers) {5 // A custom response composition chain that embeds6 // a random realistic server response delay to each `res()` call.7 return response(...transformers, context.delay())8}
Such custom response composition can later be used when creating a mocked response in a request handler:
1// src/mocks/handlers.js2import { setupWorker, rest } from 'msw'3import { res } from './res'45const worker = setupWorker(6 rest.get('/user', (req, _, ctx) => {7 // Notice how this response resolver is using a custom `res` function8 // imported at the top of this module.9 return res(ctx.json({ firstName: 'John', lastName: 'Maverick' }))10 }),11)1213worker.start()