在以下单元测试代码中:
TestModel = Backbone.Model.extend({
defaults: {
'selection': null
},
initialize: function() {
this.on('change:selection', this.doSomething);
},
doSomething: function() {
console.log("Something has been done.");
}
});
module("Test", {
setup: function() {
this.testModel = new TestModel();
}
});
test("intra-model event bindings", function() {
this.spy(this.testModel, 'doSomething');
ok(!this.testModel.doSomething.called);
this.testModel.doSomething();
ok(this.testModel.doSomething.calledOnce);
this.testModel.set('selection','something new');
ok(this.testModel.doSomething.calledTwice); //this test should past, but fails. Console shows two "Something has been done" logs.
});
第三个 ok 失败,即使该函数是从主干事件绑定中有效调用的,正如控制台演示的那样。
这非常令人沮丧,并动摇了我对 sinon.js 是否适合测试我的骨干应用程序的信心。我做错了什么,或者这是 sinon 如何检测是否已调用某事的问题?有解决方法吗?
编辑:这是我的具体示例的解决方案,基于已接受答案的猴子补丁方法。虽然它在测试本身中有几行额外的设置代码,(我不再需要模块功能)它完成了工作。谢谢,mu is too short
test("intra-model event bindings", function() {
var that = this;
var init = TestModel.prototype.initialize;
TestModel.prototype.initialize = function() {
that.spy(this, 'doSomething');
init.call(this);
};
this.testModel = new TestModel();
. . . // tests pass!
});