我在围绕我正在使用的全局对象进行 mocha 测试时遇到了一个大问题。我能够生成以下 MRE,它不会给出完全相同的错误,但会举例说明有问题的(错误的?)行为。任何见解将不胜感激。
我在 /lib
中有以下 main.js
文件:
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}
。事实上,这是我独立运行每个测试时得到的行为。例如
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)
最佳答案
test2.js
的结构应该是这样的:
describe('some test', function(){
before(function (){
global.test = {third: 3};
});
it ('messes up global', function(){
main.exec();
})
});
travisjeffery对评论中提到的GitHub问题解释道:
mocha loads the files and then runs the suites, to reliably setup your tests the setup should be within the suite.
正如@SB 指出的那样,这可能不适用于跨测试共享诸如全局变量之类的东西。
关于javascript - Mocha 全局范围界定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737252/