I am trying to test a request handler that returns a stream with MSW, however, when testing, MSW does not appear to be setting the response body as expected. Here is an example of my code
// example of request method
const apiRequest = async (route) => {
const response = await fetch(route, {
cache: 'no-cache',
method: 'post',
});
return { stream: response.body };
};
// example of test
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer([]);
it('returns stream in the response', async () => {
const url = '/mockUrl';
const encoder = new TextEncoder();
const data = encoder.encode('this is mocking a stream').buffer;
server.use(rest.post(url, (req, res, ctx) => res(
ctx.status(HttpStatus.OKAY),
ctx.set(Headers.ContentLength, data.byteLength.toString()),
ctx.set(Headers.ContentType, ContentType.Stream),
ctx.body(data),
)));
await expect(apiRequest(route)).resolves.toStrictEqual({ stream: data });
});
Whenever I run this test it fails because the body of the response is undefined and so the stream property returned by the handler is undefined. Reading through the documentation it appears the ctx.body()
method should be setting the body, but it is not. I'm not sure what I am doing wrong or if it is some kind of bug in MSW. Any help would be appreciated! Cheers!