Response transformer
Response transformer is a function that transforms a given mocked response instance. Response transformers are also referred to as "context utilities".
Standards transformers
The list of custom transformers is exposed in the ctx
argument of a response resolver. Refer to the all available transformers on the following page:
ctx.data
is a GraphQL-specific transformer), and may not be available when working with a different API type.Custom transformer
Let's create a custom response transformer to redirect in the mocked responses:
1// src/mocks/ctx/redirect.js2export function redirect(destination, statusCode) {3 return (res) => {4 res.status = statusCode5 res.headers.set('Location', destination)6 return res7 }8}
The redirect
function above is a custom response transformer: it accepts destination
and statusCode
, and returns an applicator function that modifies the mocked response to provision a redirect.
We can use this transformer by providing it as an argument to the res()
function in a response resolver:
1// src/mocks/index.js2import { redirect } from './ctx/redirect'34setupWorker(5 rest.get('/user', (req, res, ctx) => {6 return res(redirect('/v2/user', 301))7 }),8)
Composing standard transformers
It's recommended to reuse the standard transformers when creating your custom ones. This is how we could rewrite the redirect
transformer:
1// src/mocks/ctx/redirect.js2import { compose, context } from 'msw'34export function redirect(destination, statusCode) {5 return compose(6 context.status(statusCode),7 context.set('Location', destination),8 )9}
Asynchronous transformers
Response transformer may be an asynchronous function, allowing you to perform various side-effects to modify the mocked response.
1// src/mocks/ctx/jpeg.js2import { compose, context } from 'msw'34async function jpeg(base64) {5 // Converting a Base64 image to buffer via `fetch`6 // is an asynchronous action.7 const buffer = await fetch(base64).then((res) => res.arrayBuffer())89 return compose(10 context.set('Content-Length', buffer.byteLength.toString())11 context.set('Content-Type', 'image/jpeg'),12 context.body(buffer)13 )14}