当测试一个主干模型的事件已经被 sinon spy 触发时,它错误地错误:expected doSomething to be called once but was called 0 times
,即使它似乎在控制台日志被放入方法的主体时执行。测试功能如下:
it('Y U NO WORK', function() {
const events = {};
_.extend(events, Backbone.Events);
const Model = Backbone.Model.extend({
initialize: function() {
this.listenTo(events, 'doSomething', this.doSomething);
},
doSomething: function() {},
});
const model = new Model();
const spy = sinon.spy(model, 'doSomething');
events.trigger('doSomething');
sinon.assert.calledOnce(spy);
});
我知道要修复,您必须像const spy = sinon.spy(Model.prototype, 'doSomething');
在new Model()
调用之前的行中一样将 sinon spy 放在模型的原型上,但是在放入模型实例时它似乎可以正常工作,如下所示:
it('And this does work', function() {
const Model = Backbone.Model.extend();
const model = new Model();
const spy = sinon.spy(model, 'set');
model.set('foo', 'bar');
sinon.assert.calledOnce(spy);
});
好奇为什么它需要在第一个实例中放置在模型的原型上,但在第二个实例上工作?