score:0

Accepted answer

So apparently the test was still using the global fetch library, and not my patched version. The solution was to:

  1. Remove the 'isomorphic-fetch' mock (in __mocks__ at the root of the project).
  2. Import 'isomorphic-fetch' once at the root of my project with import 'isomorphic-fetch;
  3. Remove the 'isomorphic-fetch' import at the top of my api module (since it's already imported at the entrypoint
  4. Update the test to:

test:

// to make the Response constructor available
import 'isomorphic-fetch';
import { getJson } from '../api';

describe('api middleware', () => {
  describe('getJson', () => {
    beforeEach(() => {
      window.fetch = jest.genMockFunction();
    });

    it('should return the response on success', () => {
      const expected = { data: ['data'], meta: {} };
      const body = JSON.stringify(expected);
      const init = { status: 200, statusText: 'OK' };

      window.fetch.mockReturnValueOnce(Promise.resolve(new Response(body, init)));

      return getJson('http://endpoint').then(actual => expect(actual).toEqual(expected));
    });
  });
});

score:-1

Most probably because your getJson function does not use the global (window) fetch.

The way I would suggest doing it is to use Dependency Injection (DI); make getJson retrieve the the "http request" library/function (in your case fetch) and in your tests, create a mock function which is injected. The mock function will return the data that you want as part of testing.


Related Query

More Query from same tag