Mocha: Mocha stores instance state in shared global space - ie. the require cache

Created on 21 Oct 2015  路  4Comments  路  Source: mochajs/mocha

This is reflected in #995 and https://github.com/pghalliday/grunt-mocha-test/issues/108, and many other issues that keep cropping up with watch tasks even though I keep telling people to rerun tests in new processes and not reuse the same process (admittedly this pattern has other problems too)

Basically, you cannot create a new instance of mocha and add the same test files as a previously created instance. This is because require is used to run the test files and when you require them again they hit the require cache and don't run (ie. they fail to register their tests).

IMHO this is a bad design choice as instance state should not be dependent on the global state of the require cache. I suggest that addFile be changed to actually load and evaluate the file and not depend on require.

Rant over ;)

confirmed-bug

Most helpful comment

Poke

All 4 comments

Agreed, this is really bad design and should be fixed.

+1
Is https://nodejs.org/api/vm.html an option?

Edit: The following code works for me. It is possible to remove the test files manually from cache.

var Mocha = require('mocha');
var mocha = new Mocha({});
mocha.addFile('test.js');
mocha.run();

setTimeout(function() {
    delete require.cache[require.resolve('./test.js')];
    var mocha = new Mocha({});
    mocha.addFile('test.js');
    mocha.run();
},1000);

Edit2: Btw, the fields below are present in global space after first run. With a VM, these fields could be attached to a context that is available in a test file, but not in the main execution script.

[ 'before',
  'after',
  'beforeEach',
  'afterEach',
  'run',
  'context',
  'describe',
  'xcontext',
  'xdescribe',
  'specify',
  'it',
  'xspecify',
  'xit' ]

I am a bot that watches issues for inactivity.
This issue hasn't had any recent activity, and I'm labeling it stale. In 14 days, if there are no further comments or activity, I will close this issue.
Thanks for contributing to Mocha!

Poke

Was this page helpful?
0 / 5 - 0 ratings

Related issues

boneskull picture boneskull  路  76Comments

ibc picture ibc  路  59Comments

octref picture octref  路  70Comments

domenic picture domenic  路  43Comments

KylePDavis picture KylePDavis  路  71Comments