Search code examples
unit-testingjestjs

how to revert mocked function to original value in jest?


I mock a static function of a class in a test but i will effect on other test. because of nature of static function, the code is:

  test('A', async () => {
    expect.assertions(2);
    let mockRemoveInstance = jest.fn(() => true);
    let mockGetInstance = jest.fn(() => true);
    User.removeInstance = mockRemoveInstance;
    User.getInstance = mockGetInstance;
    await User.getNewInstance();
    expect(mockRemoveInstance).toHaveBeenCalled();
    expect(mockGetInstance).toHaveBeenCalled();
  });

  test('B', () => {
    let mockRemoveInstance = jest.fn();
    const Singletonizer = require('../utilities/Singletonizer');
    Singletonizer.removeInstance = mockRemoveInstance;
    User.removeInstance();
    expect.hasAssertions();
    expect(mockRemoveInstance).toHaveBeenCalled();
  });

In B test User.removeInstance() still is mocked by A test, how could reset the removeInstance() in to the original function that is defined by its class?


Solution

  • You can try using jest.spyOn

    Something like this should restore the function for you:-

        let mockRemoveInstance = jest.spyOn(User,"removeInstance");
        mockRemoveInstance.mockImplementation(() => true);
    
        User.removeInstance();
        expect(mockRemoveInstance).toHaveBeenCalledTimes(1);
    
        // After this restore removeInstance to it's original function
    
        mockRemoveInstance.mockRestore();