jefflau / jest-fetch-mock

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

3.0.3: works fine with browser fetch, won't mock with node-fetch #214

Closed jcollum closed 2 years ago

jcollum commented 2 years ago

Got 2 projects, one is a backend and the other frontend. I implemented jest-fetch-mock in the frontend first with no issues.

Now I'm implementing in the backend and it just won't actually mock fetch when the code I'm testing gets called.

Versions: node-fetch: 2.6.1 jest: 27.1.0 node: 14.17.6 jest-fetch-mock: 3.0.3

jest.config.js:

  automock: false,
  resetMocks: false,
  setupFiles: ["<rootDir>/.jest/setEnvVars.js", "<rootDir>/.jest/setupFetchMocking.js"]

.jest/setupFetchMocking.js: require('jest-fetch-mock').enableMocks()

http-io.test.js, first 2 lines:

import fetchMock, { enableFetchMocks } from "jest-fetch-mock";
enableFetchMocks()

Failing test:

      test('with no theme or filter', async () => {
        fetchMock.mockOnceIf(/.*dashboards-next.*/, () => {
          return Promise.resolve({
            status: 200,
            access_token: 'access_token',
          });
        });
        const response = await create_sso_embed_url(

First line of http-io.js, code under test: import fetch, { RequestInit } from 'node-fetch';

Now, when I debug and look at fetch I see something odd:

I gotta think this is something going on with node-fetch <-> jest-fetch-mock since this isn't happening in the other project that uses "browser" fetch.

jcollum commented 2 years ago

I changed the mocking out and used mock-service-worker instead. Works a lot better. The node-fetch and fetch and jest mocks were problematic.