Unit testing com.js中的Mocha.js和sinon spy
我有一个虚拟的脊梁。模型 和主干。我的模型的视图如下所示:Unit testing com.js中的Mocha.js和sinon spy,unit-testing,backbone.js,mocha.js,sinon,spy,Unit Testing,Backbone.js,Mocha.js,Sinon,Spy,我有一个虚拟的脊梁。模型 和主干。我的模型的视图如下所示: App.Views.NoteView = Backbone.View.extend({ template: ..., initialize: function () { this.listenTo(this.model, "change", this.render); this.render(); }, render: function () {
App.Views.NoteView = Backbone.View.extend({
template: ...,
initialize: function () {
this.listenTo(this.model, "change", this.render);
this.render();
},
render: function () {
this.$el.html(this.template({
title: this.model.get("title")
}));
return this;
}
});
对于测试,我使用mocha.js+chai+sinon,我有以下测试
describe("App.Views.NoteView", function () {
beforeEach(function () {
this.view = new App.Views.NoteView({
el: this.$fixture,
model: new App.Models.Note()
});
}
afterEach(function () {
this.view.model.destroy();
});
it("my try 1", function () {
var mySpy1 = sinon.spy(this.view, "render");
this.view.model.set({
title: "a new Title"
});
expect(this.view.render).to.have.been.calledOnce;
});
}
我试图测试的是监视render方法:当我更改模型属性时,将调用render方法。但是,即使渲染正常执行,测试也会给出错误消息
'expected render to be called once but was called 0 times'
有什么帮助吗?实际上,当视图初始化时,它会将渲染功能与其绑定。因此,当我们试图用spy绑定该渲染函数时,它是不允许的。为此,我们必须在视图初始化之前绑定spy 试试这个:
var mySpy1 = null;
describe("App.Views.NoteView", function () {
beforeEach(function () {
mySpy1 = sinon.spy(App.Views.NoteView.prototype, "render");
this.view = new App.Views.NoteView({
el: this.$fixture,
model: new App.Models.Note()
});
}
afterEach(function () {
this.view.model.destroy();
//Restore
App.Views.NoteView.prototype.render.restore();
});
it("my try 1", function () {
this.view.model.set({
title: "a new Title"
});
expect(mySpy1.called).to.be.true;
});
}很抱歉,我不确定我是否理解它总是给出错误,还是仅当您不更改模型属性时才给出错误?更改模型标题时,渲染方法会正常调用。然而,期望产生了上述错误。无论如何,我在这里发现了类似的问题:
var mySpy1 = null;
describe("App.Views.NoteView", function () {
beforeEach(function () {
mySpy1 = sinon.spy(App.Views.NoteView.prototype, "render");
this.view = new App.Views.NoteView({
el: this.$fixture,
model: new App.Models.Note()
});
}
afterEach(function () {
this.view.model.destroy();
//Restore
App.Views.NoteView.prototype.render.restore();
});
it("my try 1", function () {
this.view.model.set({
title: "a new Title"
});
expect(mySpy1.called).to.be.true;
});