Search code examples
jestjsts-jest

Best way to override auto-mocks?


I need all module functions to be auto-mocked except those I want to mock manually. I'd like to do this using factory parameter of jest.mock() by analogy with an example from jest docs (https://jestjs.io/docs/jest-object#jestrequireactualmodulename), something like this:

jest.mock('someModule', () => ({
  ...jest.requireMock('someModule'), // This doesn't work :(
  someFunction: jest.fn(() => 'someValue')
}));

I expect jest.requireMock(moduleName) to do the trick like jest.requireActual(moduleName) does, but end up with RangeError: Maximum call stack size exceeded

Is it possible to achieve my goal in such a manner? If no, what is the best practice of doing this?

jest: 24.9.0, ts-jest: 26.4.1


Solution

  • jest.mock is either automatic or manual, it cannot be both.

    Auto-mock can be created with jest.createMockFromModule and then extended. This is useful in reusable mocks in __mocks__ but generally not needed on test level.

    Unless a mock is used on import time and needs to be hosted, a way to do this per test suite is:

    jest.mock('someModule');
    
    beforeEach(() => {
      someModule.someFunction.mockReturnValue('someValue')
    });
    

    I expect jest.requireMock(moduleName) to do the trick

    This shouldn't be expected because a mock is imported inside a mock, this results in a recursion.