摩卡全球范围内的问题
我正在使用我正在使用的全局对象的mochatesting时遇到了一个大问题。 我能够产生下面的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(); }) });
我期望第一个testing会输出{another:2}
,第二个testing会打印{third: 3}
。 事实上,这是我独立运行每个testing时得到的行为。 例如
jeff@ubuntu:~/workspace/mocha-test$ mocha test/test2.js { third: 3 } ․ 1 passing (6ms)
然而,当运行两个testing与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(); }) });
在评论中提到的GitHub问题上的travisjeffery解释说:
摩卡加载文件,然后运行套件,以可靠地设置您的testing安装应该在套件内。
正如@SB指出的那样,这可能不适合跨testing共享全局variables之类的东西。
- asynchronous摩卡testing(与Chai断言库)应该失败,但被标记为通过
- 如何确保在节点上使用mocha和phantomjs进行每个testing的未触及的HTML
- Express JS与Supertest和模拟数据库的集成testing
- nodejs / mocha / nock – 模拟整个html响应
- 使用sinon.js创build一个基于真正的构造函数/原型的间谍方法的“间谍对象”
- 用MochatestingExpress和Mongoose
- Babel / Mocha:摩卡在全球安装,但describe()没有定义
- 使用cloud9的摩卡testing,从node.js执行摩卡testing
- 当使用JavaScriptdynamic加载页面内容时,使用Mocha + Zombie.js进行验收testing