jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

mockReject causes test to fail #87

Closed tjmabey closed 5 years ago

tjmabey commented 5 years ago

Maybe I am doing something wrong, but I cannot get fetch.mockReject to behave correctly.

Using mockReject causes my test to fail. Terminal output:

FAIL
 19 |   it('handles a 500 level error', () => {
    > 20 |     fetch.mockReject(new Error('errors'));
         |                      ^
      21 | 
      22 |     // assert on the response
      23 |     return actions.getFoo(0, 'token').then(res => {

      at Object.it (tests/actions.test.js:20:22)

The function that I am trying to unit test:

export async function getFoo(id, token) {
  const url = `${Config.url}foo/bar/` + id;
  const response = await fetch(url, getHeaders(token));
  if (!response.ok) {
    return {};
  }
  const json = await response.json();
  return json;
}

I expect that if the fetch fails, then !response.ok will be true and the function should return an empty object, but the test fails before that.

tjmabey commented 5 years ago

Turns out this was a non-issue for my use case due to a misunderstanding of the fetch api and promises.

My goal with my unit test was to hit the line of code where !response.ok evaluates to true. I mistakenly thought that this would happen by calling rejectMock.

After reading more about fetch, I realized I just needed to send a 500 level response code in my fetch mock. I figured out how to configure the header based on some comments on #41. I mocked the headers like this: fetch.mockResponseOnce('{ "id": 1 }', { status: 200, headers: { 'content-type': 'application/json' } });

I was using mockReject wrong, but the error I received when I tried to use it still seems odd.