Custom transformer
Use case
Sometimes the default response serializer (application/json
), provided by the default response transformer, isn't what you need and you're looking for a way to overwrite the default serialization for a response.
In this recipe we are going to write a custom response transformer that serializes BigInt
values that cannot be otherwise transformed using JSON.stringify
.
Defining a transformer
Use the createResponseComposition
API to create a custom transformer by defining a transformer.
Assign the transformer to the defaultTransformers
property, which can take multiple transformers.
A transformer receives the response, optionally it modifies the response, and then it must return the (modified) response.
The example below uses the json-bigint
package to serialize the response body.
1import { createResponseComposition } from 'msw'2import * as JSONbig from 'json-bigint'34export const customResponse = createResponseComposition({5 defaultTransformers: [6 (res) => {7 if (res.body && res.headers?.get('content-type')?.endsWith('json')) {8 res.body = JSONbig.stringify(res.body)9 }10 return res11 },12 ],13})
Using a transformer
Once the custom response transformer is defined, use it to return the response instead of using the default response method.
1import { rest } from 'msw'2import { customResponse } from './custom-response'34export const handlers = [5 rest.get('http://test.mswjs.io/me', (req, res, ctx) => {6 const me = {7 username: 'Sarah',8 balance: BigInt(1597928668063727616),9 }1011 // use customResponse instead of res12 return customResponse(ctx.json(me))13 }),14]
Asynchronous transformer
Response transformer may also be an asynchronous function returning a Promise
that resolves to the next mocked response instance.
1import { compose, context } from 'msw'23async function jpeg(base64) {4 // Converting a Base64 image to buffer via `fetch`5 // is an asynchronous action.6 const buffer = await fetch(base64).then((res) => res.arrayBuffer())78 return compose(9 context.set('Content-Length', buffer.byteLength.toString())10 context.set('Content-Type', 'image/jpeg'),11 context.body(buffer)12 )13}