Msw: ArrayBuffer responses are being stringified in mock responses

Created on 4 Aug 2020  路  3Comments  路  Source: mswjs/msw

Environment

| Name | Version |
| ------- | ------- |
| msw | 0.19.5 |
| browser | Chrome |
| OS | OSX |

Request handlers

rest.get('/file/download', async (req, res, ctx) => {

        const fileBuffer = await fetch(base64FileString).then((res) => res.arrayBuffer());

        return res(
            ctx.set('Content-Length', base64FileString.byteLength.toString()),
            ctx.set('Content-Type', 'application/octet-stream'),
            ctx.body(base64FileString)
        );
    }),

Actual request

It's suppose to send an arrayBuffer representing an XLSX file.

Current behavior

When I run through the breakpoints, it looks like it gets to the point where it's sending the MOCK_SUCCESS message from the service worker to the main thread. At that point, it running JSON.stringify on the serialized response, which is causing the response body to contain [object Object]:

lib/esm/index.js:156

const createBroadcastChannel = (event) => {
    const port = event.ports[0];
    return {
        /**
         * Sends a text message to the connected Service Worker.
         */
        send(message) {
            if (port) {
                port.postMessage(**JSON.stringify(message)**);
            }
        },
    };
};

Expected behavior

It should be sending the request as described in your recipes for binary responses:

import { setupWorker, rest } from 'msw'
import base64Image from 'url-loader!../fixtures/image.jpg'
const worker = setupWorker(
  rest.get('/images/:imageId', async (_, res, ctx) => {
    // Convert "base64" image to "ArrayBuffer".
    const imageBuffer = await fetch(base64Image).then((res) =>
      res.arrayBuffer(),
    )
    return res(
      ctx.set('Content-Length', imageBuffer.byteLength.toString()),
      ctx.set('Content-Type', 'image/jpeg'),
      // Respond with the "ArrayBuffer".
      ctx.body(imageBuffer),
    )
  }),
)
worker.start()
bug browser

All 3 comments

my fault; i didn't realize they were not supported until 0.20.0

"Adds support for binary response types (#221, #224, Binary response type recipe)."

Hey, @mentierd. Thanks for reaching out with this. I'm glad that you've found the root of the issue: the binary response type was added in the 0.20.0 release, as you've mentioned. Hope it works as expected now!

@kettanaito no problem. i absolutely love your library; cheers! many thanks

Was this page helpful?
0 / 5 - 0 ratings