mocha: The same test suite won't run twice when using mocha programmatically
When trying to execute a test suite twice, using the programmatic approach, the second time it should be executed it isn’t found. This is especially annoying when trying to execute the same test with differing configuration.
Minimal Example (the test/test.js
file contains a suite with a single always-passing test):
var Mocha = require('mocha');
function runMocha(callback) {
var mocha = new Mocha();
mocha.addFile('test/test.js');
mocha.run(function () {
callback();
});
}
runMocha(function () {
runMocha(function () {});
});
The first time mocha is run it will execute the test, the second time it will not.
The cause for this is that the second time it is required in mocha.js, the file is already cached and won’t be executed. The only solution I was able to find is deleting the cached file from require.cache
, but that doesn’t look like good practice to me at all.
About this issue
- Original URL
- State: closed
- Created 11 years ago
- Reactions: 7
- Comments: 27 (2 by maintainers)
Commits related to this issue
- Added workaround from https://github.com/mochajs/mocha/issues/995. — committed to appcelerator-archive/appium-tests by deleted user 7 years ago
- There's an idiosyncracy in Mocha where the same file can't be run twice unless we delete the `require` cache. See here: https://github.com/mochajs/mocha/issues/995 Fixes #325 — committed to trufflesuite/truffle by tcoulter 7 years ago
So I definitely had to solve this problem at least once before, yet tonight I could not remember how, so here is an example to assist my future self (or anyone else 😃 ):
Its ugly, but you should be able to call
runMochaTests()
multiple times.Deleting the cache right after running require() seems to do nicely. I suspect it’s very racy but I’ve been able to run the test hundreds of time in parallel.
How do I run tests more than once?
Output is something like:
If anyone comes across this post and is trying to run mocha tests in your browser, here is what I did to reset the tests after mocha.run()
Faced the same issue, and options above have not worked for me. I just created a helper MochaRunner class and now I can rerun the same tests.
and in both cases
test1.js
will be run!P.S. Hope it will help to someone 😉
I almost lost all of my hair. The issue is stated at the bottom of the ‘angelo’ npm module description, https://www.npmjs.com/package/angelo.
The test files are being loaded with a require, which is being cached. A simple fix would be to remove the test files cached after each run. I wouldn’t consider this hacky.
For my own quick workaround, I’m just calling
delete require.cache[testFileName]
beforeaddFile(testFileName)
.Hello.
The solution from @traviswimer is not working. My mocha tests are running only once. I can not debug it. I dont now solution.
Deleting the require.cache did not work for me. Spawning a child process did. For my use case, here was the before and after: BEOFRE:
AFTER: