0

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!

Marcus Ruddick
  • 9,795
  • 7
  • 28
  • 43

1 Answers1

0

I figured out the problem, I had called one of the functions (response.json()) that consumed the stream before returning it which then set the body to undefined. This was removed when simplifying my example, I didn't realize that's how it worked until I tried calling another function (response.text()) and got an error that illuminated the problem.

Marcus Ruddick
  • 9,795
  • 7
  • 28
  • 43