Search code examples
reactjsunit-testingjestjsrtk-queryjest-fetch-mock

RTK Query, React & fetch-mock-jest: Unrecognised Request object


I've been trying to migrate some of my current fetch logic to RTK Query to avoid duplicated fetch calls and improve data cache management. Everything is going as expected, and the application works as expected, but now tests are failing because of fetch-mock-jest library.

Whenever a test involving a component that uses RTK Query hooks is executed, it fails with the following error:

{
  status: 'FETCH_ERROR',
  error: 'TypeError: fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'
}

I've read this section of their documentation, but I don't know exactly which constructors RTKQ uses, so I don't know from which package should I import them, or how and where I should configure them.

Furthermore, my application will be a mix between RTKQ fetches (for data that needs to be called frequently, updated, and displayed in multiple places) and normal fetches (such as for downloading documents), so I don't know exactly how should I configure this to make it work in all the cases, as it was working until adding RTKQ.

Should I add some kind of configuration in setupTests.js? How should I configure jest-fetch-mock so it works with both RTKQ and normal fetch?

Thank you!


Solution

  • For anyone having this same problem, I've found that re-declaring the constructors in fetch-mock solves the issue:

    // setupTests.ts
    import fetchMockJest from 'fetch-mock-jest';
    
    // Configure standard constructors so that RTK Query works in tests with FetchMockJest
    Object.assign(fetchMockJest.config, {
      fetch,
      Headers,
      Request,
      Response,
    });
    

    Also, if you're working with RTK Query, you'll want to make sure to clean the cache after each test, otherwise your fetch calls will only be made in one of the tests:

    afterEach(() => {
      // Restore cache to allow multiple fetch calls to be performed in tests
      act(() => store.dispatch(yourRtkqApi.util.resetApiState()));
    });