在与揭示模块模式短暂的浪漫之后,我开始意识到单元测试模块的挫折。但是,我无法确定这是否是我测试模块的方法,或者是否有某种形式的解决方法。
考虑以下代码:
var myWonderfulModule = (function () {
function publicMethodA (condition) {
if(condition === 'b') {
publicMethodB();
}
}
function publicMethodB () {
// ...
}
return {
methodA : publicMethodA,
methodB : publicMethodB
}
}());
如果我想测试(使用 Jasmine)从 publicMethodA 到 publicMethodB 的各种路径。我可能会像这样写一个小测试:
it("should make a call to publicMethodB when condition is 'b'", function() {
spyOn(myWonderfulModule , 'publicMethodB');
myWonderfulModule.publicMethodA('b');
expect(myWonderfulModule.publicMethodB).toHaveBeenCalled();
});
如果我理解正确,闭包中有一个 publicMethodB 的副本无法更改。即使我之后更改 myWonderfulModule.publicMethodB :
myWonderfulModule.publicMethodB = undefined;
调用myWonderfulModule.publicMethodA
仍将运行 B 的原始版本。
The example above is of course simplified but there are plenty of scenarios I can think of where it would be convenient to unit test conditional paths through a method.
Is this a limitation of the revealing module pattern or simply a misuse of unit testing? If not what work-arounds are available to me? I'm considering moving to something like RequireJS or reverting back to non-modular code.
Any advice appreciated!