問題描述
我正在嘗試使用backbone.js、jasmine.js 和sinon.js 測試按鈕點擊.但是下面的測試用例失敗了.我正在使用間諜來跟蹤它是否被調用.你能幫我解決這個問題嗎?
I am trying to test a button click using backbone.js, jasmine.js and sinon.js. But the following test case fails. I am using a spy to track whether it is getting called or not. Can you please help me with this?
謝謝.
新任務模板
<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");
}
});
Jasmine 測試用例
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.
推薦答案
問題是你在主干已經將點擊事件直接綁定到 addTask 函數之后添加你的 spy(它在視圖的構建過程中這樣做).因此你的間諜不會被調用.
The problem is you add your spy after backbone has already bound the click event directly to the addTask function (it does that during construction of the View). Therefore your spy will not get called.
嘗試將間諜附加到視圖的原型在構建它之前.像這樣:
Try attaching the spy to a prototype of the View before you construct it. Like this:
this.addTaskSpy = sinon.spy(T.views.NewViewTask.prototype, 'addTaskSpy');
this.view = new T.views.NewTaskView();
然后記得刪除它:
T.views.NewViewTask.prototype.addTaskSpy.restore()
這篇關于沒有使用 jasmine.js 和 sinon.js 調用主干.js 點擊事件間諜的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!