jefflau/jest-fetch-mock

How can I mock the response so that I can call getReader() on the body?

Closed this issue · 1 comments

I'd like to write a test related to the following code:

const response = await fetch(url)
const reader = response.body.getReader()
while (true) {
  const { done, value } = await reader.read()
  ...
}
...

Is this possible? How would I go about mocking the response to get a mockReader?
Thanks in advance!

I figured something out, but i'm overriding the mock rather than using it...

  const mockRead = jest.fn()
  mockRead.mockReturnValueOnce({ done: false, value: 'this is my blob text' })
  mockRead.mockReturnValueOnce({ done: true })
  jest.spyOn(global, 'fetch').mockImplementation(() =>
    Promise.resolve().then(() => ({
      body: {
        getReader: () => ({ read: mockRead })
      }
    }))
  )

This wouldn't work if I tried to put the same body in fetch.mockResponseOnce