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.....*/);
});