在追求100%的代码覆盖率的,我试图用摩卡来测试我的javascript模块AMD
下正确加载,CommonJS/Node
,并browser
条件。我使用的模式如下:如何在mocha测试中模拟全局变量(定义,模块,窗口)?
我-module.js
(function(global){
function MyClass(){}
// AMD
if(typeof define === 'function' && define.amd){
define(function(){
return MyClass;
});
// CommonJS/Node
} else if (typeof module !== 'undefined' && module.exports){
module.exports = MyClass;
// Browser
} else {
global.MyClass = MyClass;
}
})(this);
因为我跑我的节点测试,define
是从来没有定义,总是被定义module
;所以“CommonJS/Node”条件是唯一经过测试的条件。
我至今尝试过是这样的:
我-module.test.js
var MyClass = require('./my-module');
describe('MyClass', function(){
// suite of tests for the class itself
// uses 'var instance = new MyClass();' in each test
// all of these tests pass
});
describe('Exports', function(){
// suite of tests for the export portion
beforeEach(function(){
MyClass = null; // will reload module for each test
define = null; // set 'define' to null
module = null; // set 'module' to null
});
// tests for AMD
describe('AMD', function(){
it('should have loaded as AMD module', function(){
var define = function(){};
define.amd = true;
MyClass = require('./my-module'); // might be cached?
// hoping this reloads with 'define' in its parent scope
// but it does not. AMD condition is never reached.
expect(spy).to.have.been.called(); // chai spy, code omitted
});
});
});
我使用的间谍,以检查是否define
被调用,但模块没有显示任何可用的define
重新加载的迹象。我怎样才能做到这一点?
并有没有一种安全的方法取消module
,以便我可以测试浏览器的情况?
感谢您的答案!这看起来很有希望,明天就会测试一下! – SteamDev
有用的模块,但在这种特殊情况下没有雪茄。我认为这可能是因为我需要全局可用于包装IIFE,而不是导出的类本身。 – SteamDev