backbone.js click event spy is not getting called using jasmine.js and sinon.js(没有使用 jasmine.js 和 sinon.js 调用主干.js 点击事件间谍)
问题描述
我正在尝试使用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 点击事件间谍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:没有使用 jasmine.js 和 sinon.js 调用主干.js 点击事件


- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01