mswMock Service Worker
  1. Recipes
  2. Binary response type

Binary response type

Providing the ctx.body() utility function with a BufferSource object will use that buffer as the mocked response's body. Support of binary data allows to send any kind of media content (images, audio, documents) in a mocked response.

Example

Browser

Here is an example of a mocked response that sends a local image:

1import { setupWorker, rest } from 'msw'
2import base64Image from 'url-loader!../fixtures/image.jpg'
3
4const worker = setupWorker(
5 rest.get('/images/:imageId', async (_, res, ctx) => {
6 // Convert "base64" image to "ArrayBuffer".
7 const imageBuffer = await fetch(base64Image).then((res) =>
8 res.arrayBuffer(),
9 )
10
11 return res(
12 ctx.set('Content-Length', imageBuffer.byteLength.toString()),
13 ctx.set('Content-Type', 'image/jpeg'),
14 // Respond with the "ArrayBuffer".
15 ctx.body(imageBuffer),
16 )
17 }),
18)
19
20worker.start()
Ensure that the Content-Type header of the response properly describes your content.

NodeJS

Here is an example of a mocked response that reads an image from the file system and sends it in the mocked response:

1import * as path from 'path'
2import * as fs from 'fs'
3import { setupServer } from 'msw/node'
4import { rest } from 'msw'
5
6const server = setupServer(
7 rest.get('/images/:imageId', (_, res, ctx) => {
8 // Read the image from the file system using the "fs" module.
9 const imageBuffer = fs.readFileSync(
10 path.resolve(__dirname, '../fixtures/image.jpg'),
11 )
12
13 return res(
14 ctx.set('Content-Length', imageBuffer.byteLength.toString()),
15 ctx.set('Content-Type', 'image/jpeg'),
16 // Respond with the "ArrayBuffer".
17 ctx.body(imageBuffer),
18 )
19 }),
20)
21
22server.listen()