I have multiple .js test files and I would like to be able to run the tests in each file multiple times. For example, I would like to run each 5 or 10 times in a row. Even if it's just one file at a time, but the same file multiple times.
I was trying to unload the module from memory and then loading it again multiple time to see if it worked, but it doesn't. Check:
const testFilePath = './myFileWithOneMochaTestSuit.js';
for(let i = 0; i < 5; i ) {
delete require.cache[require.resolve(test)]; // Unloading the module in memory
require(testFilePath);
}
The reason why I want to do this is because I have some integration tests that sometimes can fail. I want to be able to run these tests as many times as I need to analyze them when they fail.
All my test files look something like this:
// test1.js
describe('test suit 1', () => {
//...
before(() => {
//...
});
it(`test 1...`, async () => {
//...
});
it('test 2', () => {
//...
});
// more tests
});
// test2.js
// test2.js
describe('test suit 2', () => {
//...
before(() => {
//...
});
it(`test 1...`, async () => {
//...
});
it('test 2', () => {
//...
});
// more tests
});
So, what I need is to be able to run the test suite in test1.js
multiple times in a row. And then test2.js
multiple times in a row. Etc.
I have not been able to do that.
Any help would be appreciated.
I tried loading the files with require
multiple times, but they only run once, the first time.
I tried removing the cached module in memory and loading it again with require
, but didn't work.
CodePudding user response:
Weird! It started working all of a sudden once I assigned the returned value of require
to a variable and print it like:
for(let i = 0; i < 5; i ) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
const m = require(testFilePath);
console.log(m);
}
But then I removed the console.log(m)
to see if it kept working, and it did:
for(let i = 0; i < 5; i ) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
const m = require(testFilePath);
}
Finally I removed the const m =
to see if it keeps working, and it did!
for(let i = 0; i < 5; i ) {
delete require.cache[require.resolve(testFilePath)]; // Unloading the module in memory
require(testFilePath);
}
So I basically got back to where I started, but now it was working and loading the modules and unloading the test files and running the tests multiple times as I wanted.
I don't know how this happened with basically no difference in the code, but I'm glad it did.