Search code examples
jestjsts-jest

Jest. The original function is called instead of the mock function


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!


Solution

  • The issue you’re facing is due to the way the Jest mocking system works. When you’re mocking a module with jest.mock, the mock is applied at the time of import. This means that when testBar is imported, it’s still referencing the original testBar1, not the mocked version.

    // Mock the function after import
    Tools.testBar1 = jest.fn(() => 'mocked test2');
    
    test('should mock functions correctly', () => {
      const result = Tools.testBar();
      expect(result).toBe('testmocked test2');
    });