How to reload a Node.js module


Recently, I needed to reload (remove and re-require) a Node.js module during testing.

I found a Stackoverflow answer that deleted the module from the require.cache before requiring it again:

delete require.cache[require.resolve('./path/to/module')];
require('./path/to/module');

Mocha

Applying this approach to my Mocha test:

const myModule = require('./my-module');

beforeEach(() => {
  delete require.cache[require.resolve('./my-module')];
});

it('imports the same module but as a separate instance', () => {
  expect(require('./my-module')).not.toBe(myModule);
});

Jest

Jest, on the other hand, makes it easy with jest.resetModules:

const myModule = require('./my-module');

beforeEach(() => {
  jest.resetModules();
});

it('imports the same module but as a separate instance', () => {
  expect(require('./my-module')).not.toBe(myModule);
});

For module isolation, there’s jest.isolateModules which creates a sandbox registry for modules loaded inside a callback function.



If you enjoyed this post, please consider supporting this site!