'Reset single module with Jest

jest.resetModules() clears the require cache for all modules but is there a way to clear it for just a single module? Can't use require.cache as Jest appears to bypass it.

I'm testing a Node module which is stateful (i.e. it relies on the fact that multiple calls to require return the same instance). For my test I need to reset the state of the module to test different scenarios. jest.resetModules() works but then I need to re-require some other mocked modules which didn't need to be reset.



Solution 1:[1]

An example of mocking modules (with factories) for some tests, and restoring for others within a test file

describe("some tests", () => {
  let subject;

  describe("with mocks", () => {
    beforeAll(() => {
      jest.isolateModules(() => {
        jest.doMock("some-lib", () => ({ someFn: jest.fn() })); // .doMock doesnt hoist like .mock does when using babel-jest
        subject = require('./module-that-imports-some-lib');
      });
    });

    // ... tests when some-lib is mocked
  });

  describe("without mocks - restoring mocked modules", () => {
    beforeAll(() => {
      jest.isolateModules(() => {
        jest.unmock("some-lib");
        subject = require('./module-that-imports-some-lib');
      });
    });

    // ... tests when some-lib is NOT mocked

  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1