backbone.js、jasmine.js、sinon.js を使用してボタンのクリックをテストしようとしています。しかし、次のテスト ケースは失敗します。呼び出されているかどうかを追跡するためにスパイを使用しています。これについて助けていただけませんか?
ありがとう。
新しいタスクテンプレート
<script id='new_task_template' type='text/template'>
<input type='text' id='new_task_name' name='new_task_name'></input>
<button type='button' id='add_new_task' name='add_new_task'>Add Task</button>
</script>
新しいタスクビュー
T.views.NewTaskView = Backbone.View.extend({
tagName: 'section',
id: 'new_task_section',
template : _.template ( $("#new_task_template").html() ),
initialize: function(){
_.bindAll( this, 'render', 'addTask');
},
events:{
"click #add_new_task" : "addTask"
},
render: function(){
$(this.el).html( this.template() );
return this;
},
addTask: function(event){
console.log("addTask");
}
});
ジャスミンテストケース
describe("NewTaskView", function(){
beforeEach( function(){
this.view = new T.views.NewTaskView();
this.view.render();
});
it("should #add_new_task is clicked, it should trigger the addTask method", function(){
var clickSpy = sinon.spy( this.view, 'addTask');
$("#add_new_task").click();
expect( clickSpy ).toHaveBeenCalled();
});
});
ジャスミン出力
NewTaskView
runEvents
runshould #add_new_task is clicked, it should trigger the addTask method
Expected Function to have been called.
ベストアンサー1
問題は、バックボーンがクリック イベントを addTask 関数に直接バインドした後にスパイを追加することです (これはビューの構築中に行われます)。したがって、スパイは呼び出されません。
スパイをビューのプロトタイプに取り付けてみる前にこれを構築します。次のようにします。
this.addTaskSpy = sinon.spy(T.views.NewViewTask.prototype, 'addTaskSpy');
this.view = new T.views.NewTaskView();
そして、それを削除することを忘れないでください:
T.views.NewViewTask.prototype.addTaskSpy.restore()