我在使用我正在使用的全局对象的mocha测试中遇到了大问题。我能够生成以下MRE,它没有给出完全相同的错误,但举例说明了有问题的(错误的?)行为。任何见解都会非常感激。
我在main.js
中有以下/lib
文件:
exports.exec = function(){
console.log(test);
}
然后/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();
})
});
最后,这是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();
})
});
我希望第一个测试输出{another:2}
,第二个测试打印{third: 3}
。实际上,这是我独立运行每个测试时得到的行为。 e.g。
jeff@ubuntu:~/workspace/mocha-test$ mocha test/test2.js
{ third: 3 }
․
1 passing (6ms)
但是,当使用npm包should
和mocha
(1.16.1)运行测试时,我得到以下输出:
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)
答案 0 :(得分:9)
test2.js
的结构应如下:
describe('some test', function(){
before(function (){
global.test = {third: 3};
});
it ('messes up global', function(){
main.exec();
})
});
travisjeffery在评论中提到的GitHub问题上解释说:
mocha加载文件然后运行套件,以便可靠地设置测试,设置应该在套件中。
正如@SB指出的那样,这可能不适合跨测试分享全局变量之类的东西。