1

I have been trying to debug why this is happening. I am unable to mock a dependent function if its from the same module as the function calling it. But I am able to overcome this if the mocked function is moved to a separate module which is different from the module of the function calling it.

Not working scenario
Module A (filename.ts)

export const callingFunction = () => {
  //....statements
  dependentFunction();
}

export const dependantFunction = () => {
  //....statements
  //resolve with something
}

filename.test.ts

import { callingFunction } from './fileName'

jest.mock('./fileName',() =>  ({
 ...jest.requireActuals('./fileName'),
 dependentFunction: jest.fn().mockImplementation(/*....Mocked implementation*/)
})

test('...test case description...', () => {
  const callingFunctionRespose: any = callingFunction();
  expect(callingFunctionResponse).toEqual(/*....something.....*/);
});

The above mock does not override the dependentFunction exported by the fileName.ts module. Instead, when the exported function callingFunction() is called, it uses the implementation defined in the module. (Found this out by logging the function definitions.

But this behaviour is not observed when the dependant function is moved to it own separate module.

Working scenario
fileName.ts

import { dependentFunction } from './dependentFunctions'

export const callingFunction = () => {
  //....statements
  dependentFunction();
}

dependentFunctions.ts

export const dependantFunction = () => {
  //....statements
  //resolve with something
}

fileName.test.ts

import { callingFunction } from './fileName'

jest.mock('./dependentFunctions',() =>  ({
 ...jest.requireActuals('./dependentFunctions'),
 dependentFunction: jest.fn().mockImplementation(/*....Mocked implementation*/)
})

test('...test case description...', () => {
  const callingFunctionRespose: any = callingFunction();
  expect(callingFunctionResponse).toEqual(/*....something.....*/);
});
Gaurav Thantry
  • 753
  • 13
  • 30
  • See https://stackoverflow.com/q/45111198/3001761 (but specifically see https://stackoverflow.com/a/70066090/3001761 and _don't_). – jonrsharpe Feb 07 '22 at 23:05

2 Answers2

1

You can import the functions as a module

import * as module from './fileName'

To mock the implementation you can do

jest.spyOn(module, 'dependentFunction').mockImplementation(/*....Mocked implementation*/)

To call the other function, use module.callingFunction()

Samantha
  • 751
  • 2
  • 6
  • 18
-1

Appologies for the late update. But the solution in the following article was the fix:

https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f

Gaurav Thantry
  • 753
  • 13
  • 30