I’m facing an issue with function mocking in Jest, especially when one function calls another within itself. I’m using Jest to test the tools module where testBar calls testBar1. I’m trying to mock testBar1 to ensure that testBar uses the mocked value, but it’s not working as expected.
Here’s my current approach:
// Tools.test.ts
import { testBar } from './Tools';
jest.mock('./Tools', () => {
const originalModule = jest.requireActual('./Tools');
return {
...originalModule,
testBar1: jest.fn(() => 'mocked test2'),
};
});
test('should mock functions correctly', () => {
const result = testBar();
expect(result).toBe('testmocked test2');
});
// Tools.ts
export const testBar1 = () => {
return 'original test2';
};
export const testBar = () => {
return 'test' + testBar1();
};
The problem is that testBar still uses the original testBar1 value instead of the mocked one. How can I fix this issue?
Thank you for your help!
iglushkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.