考虑以下茉莉花规格:
describe("something.act()", function() {
it("calls some function of my module", function() {
var mod = require('my_module');
spyOn(mod, "someFunction");
something.act();
expect(mod.someFunction).toHaveBeenCalled();
});
});
这工作得很好。像这样使它变绿:
something.act = function() { require('my_module').someFunction(); };
现在看看这个:
describe("something.act()", function() {
it("calls the 'root' function of my module", function() {
var mod = require('my_module');
spyOn(mod); // jasmine needs a property name
// pointing to a function as param #2
// therefore, this call is not correct.
something.act();
expect(mod).toHaveBeenCalled(); // mod should be a spy
});
});
这是我想用这个规范测试的代码:
something.act = function() { require('my_module')(); };
在过去的几个月里,这让我多次陷入困境。一种理论上的解决方案是替换 require() 并返回使用 createSpy() 创建的间谍。但是 require() 是不可阻挡的野兽:它是每个源文件/模块中函数的不同“副本”。在规范中将其存根不会替换“testee”源文件中真正的 require() 函数。
另一种方法是在加载路径中添加一些假模块,但对我来说它看起来太复杂了。
任何的想法?