1

Is there a way to tell the testing framework (nodeunit, mocha, should) to reload a 'required' module for each test?

I have multiple tests for my module, and I find that since Node's module system caches the module upon the first require(), subsequent test runs are hitting the same object (with its old state, including injected mock objects that no longer apply to the next test in the suite.)

So what's happening is that TDD has driven me to create a module like:

// my module
module.exports = function(dep1, dep2) {
    // code goes here, makes use of dep1/dep2
}

My first test injects a mock for dep1; next test injects a mock for dep2. But since require() always returns the same instance of my module, the second test's mocks never get properly injected. Test are all operating on the same Object Under Test, which is bad.

One solution would be to redesign the module to support "new", and return a new instance each time. Before I go down that route, is there a way to force a module to reload in a test env?

George Armhold
  • 30,824
  • 50
  • 153
  • 232

0 Answers0