- 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如何检测是否已经调用了某些东西?有解决方法吗?
编辑:这是我的具体例子的解决方案,基于接受答案的猴子补丁方法.虽然它在测试中有几行额外的设置代码,(我不再需要模块功能)但它完成了工作.谢谢,亩太短了
- 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!
- });
解决方法
var spy = sinon.spy(object,“method”);
Creates a spy for
object.method
and replaces the original method with the spy.
所以this.spy(this.testModel,’doSomething’)实际上是这样做的:
- var m = this.testModel.doSomething;
- this.testModel.doSomething = function() {
- // Spying stuff goes here...
- return m.apply(this,arguments);
- };
这意味着在initialize中绑定事件处理程序时,testModel.doSomething是一个不同的函数:
- this.bind('change:selection',this.doSomething);
在你附上间谍之后. Backbone事件调度程序将调用原始的doSomething方法,但该方法没有Sinon检测.当您手动调用doSomething时,您将调用间谍添加的新函数,并且该函数具有Sinon检测.
如果你想使用Sinon测试你的Backbone事件,那么你必须安排在绑定任何事件处理程序之前将Sinon间谍调用应用于模型,这可能意味着挂钩初始化.
也许你可以修补模型的初始化,以便在绑定任何事件处理程序之前添加必要的间谍调用:
- var init = Model.prototype.initialize;
- Model.prototype.initialize = function() {
- // Set up the Spy stuff...
- init.apply(this,arguments);
- };
演示:http://jsfiddle.net/ambiguous/C4fnX/1/
您还可以尝试使用以下内容对您的模型进行子类化:
- var Model = Backbone.Model.extend({});
- var TestModel = Model.extend({
- initialize: function() {
- // Set up the Spy stuff...
- Model.prototype.initialize.apply(this,arguments);
- }
- });
然后使用TestModel而不是Model,这将在TestModel中为您提供一个检测版本的Model,而不必在正常的生产就绪模型中包含一堆特定于测试的代码.缺点是使用Model的任何其他东西都需要进行子类化/修补/ …以使用TestModel.
演示:http://jsfiddle.net/ambiguous/yH3FE/1/
您可以通过以下方式解决TestModel问题:
- var OriginalModel = Model;
- Model = Model.extend({
- initialize: function() {
- // Set up the Spy stuff...
- OriginalModel.prototype.initialize.apply(this,arguments);
- }
- });
但你必须得到正确的订购,以确保每个人都使用新模型而不是旧模型.