Reload module with Node.js require

In Node.js using require to load a module will cache the result. If a module exports a constructed object it will be treated as a singleton, meaning it will only be constructed once

While this is useful and performant for your application, it may not be ideal when performing testing.

Under the covers, require() uses require.resolve() to resolve the dependency path.

require() also places the resolved dependency in the cache. Fortunately, the cache is dictionary with the key of the dependency path. This means, you can simply delete the cache key and require will reload the dependency!

So that means you can clear the cache using delete as such:

delete require.cache[require.resolve('./dep')];  

So how does it work. Lets take a look a simple module that returns an object.

let dep = {  
  created: Date.now()
};
module.exports = dep;  

If we use require on this module, it will always return the same date since it loads the instance from the cache.

describe('require', () => {  
    it('caches the instance', () => {
        let dep1 = require('./dep');
        let dep2 = require('./dep');
        expect(dep1.created).to.equal(dep2.created);
    });
});

However, we can clear the cache between uses to allow the module to be reconstructed.

describe('require', () => {  
    it('reconstructs the instance', () => {
        let dep1 = require('./dep');
        delete require.cache[require.resolve('./dep')];
        let dep2 = require('./dep');
        expect(dep1.created).to.not.equal(dep2.created);
    });
});
comments powered by Disqus