Jest.mock is evaulated multiple times

Viewed 14

I used jest.mock to modify the return value of some module functions that were used by the functions I'm trying to test. This has worked so far, however I cannot test the calls to some of these functions. For eg,

import {modFuncOne} from '~/modules/mod1';
import {modFuncTwo} from '~/modules/mod2';

jest.mock('~/modules/mod1', () => {
  console.log('evaluating mod1');
  return {
    ...jest.requireActual('~/modules/mod1'),
    modFuncOne: jest.fn(),
  };
});

jest.mock('~/modules/mod2', () => {
  console.log('evaluating mod2'); // possible for this to print twice
  return {
    ...jest.requireActual('~/modules/mod2'),
    modFuncTwo: jest.fn(),
  };
});

Imagine the tested function runs both modFuncOne and modFuncTwo. Then, it is possible that in the jest test, expect(modFuncOne).toBeCalledTimes(1) can pass but expect(modFuncTwo).toBeCalledTimes(1) fails. When printing out to console the .mock property of the mocked functions, modFuncOne.mock will have some values whereas modFuncTwo.mock will simply show empty arrays ({ calls: [], instances: []... }). This only happens because the import statement in the .test file duplicates the module and thus the functions imported are a separate existence from the ones used in the tested function, even if behaviour has been overridden in both cases. Would like to understand why this happens so inconsistently (in my original code I mocked 4 modules and only one of the 4 actually run into this problem) and if possible, what I can do to prevent it/resolve the issue of call tracking.

0 Answers
Related