jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
881 stars 116 forks source link

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

Closed jestrickler closed 2 years ago

jestrickler commented 2 years ago

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!

jestrickler commented 2 years ago

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