我正在为 Backbone View 编写一个测试,以测试在获取模型后是否调用了渲染函数。测试是:
beforeEach(function () {
$('body').append('<div class="sidebar"></div>');
profileView = new ProfileView();
});
it('should call the render function after the model has been fetched', function (done) {
profileView.model = new UserModel({md5: 'd7263f0d14d66c349016c5eabd4d2b8c'});
var spy = sinon.spy(profileView, 'render');
profileView.model.fetch({
success: function () {
sinon.assert.called(spy);
done();
}
});
});
我正在使用 Sinon Spies 将间谍对象附加到 profileView 视图对象的渲染函数。
观点是:
var ProfileView = Backbone.View.extend({
el: '.sidebar'
, template: Hogan.compile(ProfileTemplate)
, model: new UserModel()
, initialize: function () {
this.model.bind('change', this.render, this);
this.model.fetch();
}
, render: function () {
$(this.el).html(this.template.render());
console.log("Profile Rendered");
return this;
}
});
在测试中调用 fetch 之后,更改事件被触发并且视图的渲染函数被调用,但是 Sinon Spy 没有检测到渲染被调用并且失败。
作为一个实验,我尝试在测试中调用 render 函数来查看 Spy 是否识别了它:
it('should call the render function after the model has been fetched', function (done) {
profileView.model = new UserModel({md5: 'd7263f0d14d66c349016c5eabd4d2b8c'});
var spy = sinon.spy(profileView, 'render');
profileView.render();
profileView.model.fetch({
success: function () {
sinon.assert.called(spy);
done();
}
});
});
间谍检测到调用是在上述情况下进行的。
有谁知道为什么间谍在我的初始测试中没有识别渲染调用?