Reset single module with Jest

As explained in the question, jest.resetModules() resets the module cache, which is useful your module keeps some local state and you want to get rid of that state between tests.

The problem with resetModules is that it resets everything but sometimes you want only some of the modules to be reset.

Since Jest 24 you can now use the jest.isolateModules to do this.

Let’s say you have a module that keeps state:

module.js

exports.a = 1
exports.add = function (a) {
  return exports.a += a;
}

module.test.js

test('adds 1 to counter', () => {
  jest.isolateModules(() => {
    const myModule = require('./module');
    expect(myModule.add(1)).toBe(2);
    expect(myModule.add(1)).toBe(3);
  });
});

test('adds 2 to counter', () => {
  jest.isolateModules(() => {
    const myModule = require('./module');
    expect(myModule.add(2)).toBe(3);
    expect(myModule.add(2)).toBe(5);
  });
});

Basically with after every jest.isolateModules() call, the next time the module is required it will be have a fresh state.

Leave a Comment