【发布时间】:2012-02-25 03:47:36
【问题描述】:
我正在尝试使用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");
}
});
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.
【问题讨论】:
-
视图在 DOM 中的什么位置呈现自身?模板甚至在规范中可用吗?可能 button#add_new_task 在 Jasmine 规范运行器的 DOM 中不存在,因此
$("#add_new_task").click();无效。如果您确定使用正确的模板呈现视图,则可以使用 NewTaskView 的元素作为 jquery 函数的上下文:$('#add_new_task', this.view.el).click();。 -
我想这个问题已经在这里回答了:stackoverflow.com/questions/8441612/…
标签: javascript jquery backbone.js jasmine sinon