mswMock Service Worker
  1. Basics
  2. Response transformer

Response transformer

Response transformer is a function that transforms a given mocked response instance.

When using Mock Service Worker you don't have to write response transformers. Please treat this page as purely educational.

Example

For illustrational purposes let's create a simple response transformer:

1// src/mocks/redirectStatus.js
2export function redirectStatus(res) {
3 res.status = 301
4 return res
5}

The transformer above would always set the HTTP status code of the given response to 301.

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 { redirectStatus } from './redirectStatus'
3
4setupWorker(
5 rest.get('/user', (req, res, ctx) => {
6 return res(redirectStatus)
7 }),
8)

Of course, setting a fixed status code is rarely what you want. To parametrize this behavior, response transformers are often wrapped in high-order functions. In fact, this is how all of the standard-transformers are implemented (i.e. ctx.status(301)).

Standards transformers

Please see the list of standard response transformers available in the ctx argument of a response resolver.

Some response transformers are specific to the type of the API you are mocking (REST API or GraphQL), any may not be available when working with a different API type.