I'm having a big problem with my mocha tests around a global object I'm using. I'm able to produce the following MRE which doesn't give the exact same error, but exemplifies the problematic (buggy?) behavior. Any insight would be much appreciated.
I have the following main.js
file in /lib
:
exports.exec = function(){
console.log(test);
}
Then the following in /test/test.js
:
var should = require('should');
var main = require('../lib/main');
global.test = {something: 1};
describe('normal test', function(){
beforeEach(function(){
global.test = {another: 2};
}),
afterEach(function(){
delete global.test;
});
it ('might work with global', function(){
main.exec();
})
});
Finally, this is test/test2.js
:
var should = require('should');
var main = require('../lib/main');
global.test = {third: 3};
describe('some test', function(){
it ('messes up global', function(){
main.exec();
})
});
I expect that the first test would output {another:2}
and the second would print {third: 3}
. Indeed, this is the behavior I get when I run each test independently. e.g.
jeff@ubuntu:~/workspace/mocha-test$ mocha test/test2.js
{ third: 3 }
․
1 passing (6ms)
However, when running both test with npm packages should
and mocha
(1.16.1), I get the following output:
jeff@ubuntu:~/workspace/mocha-test$ mocha
{ another: 2 }
․․
1 passing (6ms)
1 failing
1) some test messes up global:
ReferenceError: test is not defined
at Object.exports.exec (/home/jeff/workspace/mocha-test/lib/main.js:3:15)
at Context.<anonymous> (/home/jeff/workspace/mocha-test/test/test2.js:8:10)
at Test.Runnable.run (/usr/lib/node_modules/mocha/lib/runnable.js:211:32)
at Runner.runTest (/usr/lib/node_modules/mocha/lib/runner.js:355:10)
at /usr/lib/node_modules/mocha/lib/runner.js:401:12
at next (/usr/lib/node_modules/mocha/lib/runner.js:281:14)
at /usr/lib/node_modules/mocha/lib/runner.js:290:7
at next (/usr/lib/node_modules/mocha/lib/runner.js:234:23)
at Object._onImmediate (/usr/lib/node_modules/mocha/lib/runner.js:258:5)
at processImmediate [as _immediateCallback] (timers.js:330:15)
test2.js
should be structured like this:
describe('some test', function(){
before(function (){
global.test = {third: 3};
});
it ('messes up global', function(){
main.exec();
})
});
travisjeffery on the GitHub issue mentioned in the comment explains:
mocha loads the files and then runs the suites, to reliably setup your tests the setup should be within the suite.
As @SB points out, this may not be amenable to sharing things like global variables across tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With