モデルをフェッチした後にレンダリング関数が呼び出されていることをテストするために、バックボーン ビューのテストを作成しています。テストは次のとおりです。
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 が呼び出された後、change イベントが発生し、ビューの render 関数が呼び出されますが、Sinon Spy は render が呼び出されていることを検出せず、失敗します。
実験として、テストで 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();
}
});
});
スパイは、上記の場合にコールが行われたことを検出しました。
私の最初のテストで Spy がレンダリング呼び出しを識別しない理由を誰か知っていますか?