How to prevent Mocha from preserving require cache between test files?

Viewed 1041

I am running my integration test cases in separate files for each API.

Before it begins I start the server along with all services, like databases. When it ends, I close all connections. I use Before and After hooks for that purpose. It is important to know that my application depends on an enterprise framework where most "core work" is written and I install it as a dependency of my application.

I run the tests with Mocha.

When the first file runs, I see no problems. When the second file runs I get a lot of errors related to database connections. I tried to fix it in many different ways, most of them failed because of the limitations the Framework imposed me.

Debugging I found out that Mocha actually loads all files first, that means that all code written before the hooks and the describe calls is executed. So when the second file is loaded, the require.cache is already full of modules. Only after that the suite executes the tests sequentially.

That has a huge impact in this Framework because many objects are actually Singletons, so if in a after hook it closes a connection with a database, it closes the connection inside the Singleton. The way the Framework was built makes it very hard to give a workaround to this problem, like reconnecting to all services in the before hook.

I wrote a very ugly code that helps me before I can refactor the Framework. This goes in each test file I want to invalidate the cache.

function clearRequireCache() {
    Object.keys(require.cache).forEach(function (key) {
        delete require.cache[key];
    });
}

before(() => {
    clearRequireCache();
})

It is working, but seems to be very bad practice. And I don`t want this in the code.

As a second idea I was thinking about running Mocha multiple times, one for each "module" (as of my Framework) or file.

"scripts": {
   "test-integration" : "./node_modules/mocha/bin/mocha ./api/modules/module1/test/integration/*.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file1.integration.js && ./node_modules/mocha/bin/mocha ./api/modules/module2/test/integration/file2.integration.js"
}

I was wondering if Mocha provides a solution for this problem so I can get rid of that code and delay the code refacting a bit.

0 Answers
Related