考虑以下茉莉规范:
这个工作很完美。类似这样的东西会让它变成绿色:
现在看一下这个:
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')(); };
在过去的几个月中,这个问题已经困扰了我好几次。一个理论上的解决方案是用createSpy()替换require()并返回一个spy。但是,require()是一个不可阻挡的野兽:它是每个源文件/模块中不同的函数"副本"。在测试规范中对其进行打桩(stubbing)将无法替换"testee"源文件中真正的require()函数。
另一种选择是向加载路径添加一些假模块,但对我来说看起来太复杂了。
有什么想法吗?