mswMock Service Worker
  1. Basics
  2. Response transformer

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:

Context/docs/api/context
Some response transformers are specific to the type of the API you are mocking (i.e. ctx.data is a GraphQL-specific transformer), any 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.js
2export function redirect(destination, statusCode) {
3 return (res) => {
4 res.status = statusCode
5 res.headers.set('Location', destination)
6 return res
7 }
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.js
2import { redirect } from './ctx/redirect'
3
4setupWorker(
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.js
2import { compose, context } from 'msw'
3
4export 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.js
2import { compose, context } from 'msw'
3
4async 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())
8
9 return compose(
10 context.set('Content-Length', buffer.byteLength.toString())
11 context.set('Content-Type', 'image/jpeg'),
12 context.body(buffer)
13 )
14}