jefflau / jest-fetch-mock

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

Getting TypeError: isMocking is not a function or its return value is not iterable on vesion 3.0.3 #194

Closed pprasanth closed 3 years ago

pprasanth commented 3 years ago

Tried run test case with mock enabled for one of my action creator and failing due to isMocking is not a function or return value is not iterable.

Versions:

whatwg-fetch "2.0.4"
jest-fetch-mock "3.0.3"

setupJest.js require('jest-fetch-mock').enableMocks(); code:

function fetchWithoutDispatch(url, config) {
  return fetch(url, config)
    .then((data) => {
      if (data.ok && data.status === 204) {
        return data;
      }
      return data.json();
    });
}

test code:

test('on fetchWrapper without dispatch', (Done) => {
    const args = {
      ...config.configuration,
      hideLoader: true,
    };
    fetchWrapper.mockResponse(JSON.stringify([]));
    actionHelper.fetchIt(args).then((data) => {
      expect(data).toEqual([]);
      Done();
    });
  });

Error:

● Common ActionHelper › on fetchWrapper without dispatch

    TypeError: isMocking is not a function or its return value is not iterable

      55 |
      56 | function fetchWithoutDispatch(url, config) {
    > 57 |   return fetch(url, config)
         |          ^
      58 |     .then((data) => {
      59 |       if (data.ok && data.status === 204) {
      60 |         return data;

      at ../../node_modules/jest-fetch-mock/src/index.js:96:29
      at fetchWithoutDispatch (src/actions/actionHelper.js:57:10)
cam8001 commented 3 years ago

Try adding

    "resetMocks": false,

to your package.json jest config as mentioned here: https://github.com/jefflau/jest-fetch-mock/issues/184#issuecomment-781421460

I did and it resolved the issue.

Neruell commented 3 years ago

@cam8001 Thanks, that worked for me too.

ambroselittle commented 5 months ago

For those who actually want to use resetMocks, this approach worked for us. In your test setup file:

import fetchMock from 'jest-fetch-mock';

beforeEach(() => {
  // we have `resetMocks` as true, so between each test, it is reset
  fetchMock.enableMocks();
  // trial and error found that need to do both enable and do before each test
  fetchMock.doMock();
});

We previously had enableMocks set like this, but were seeing the error here. Adding the following doMock appears to "re-enable" them. From an API expectation POV, I'd expect enableMocks to do whatever doMock is doing, in that it would always re-enable, even if resetMocks is true. But anyhow, this is an OK enough work around and wanted to share for others who may not want to disable resetMocks.