gpt4 book ai didi

javascript - 没有使用 jasmine.js 和 sinon.js 调用backbone.js 点击事件 spy

转载 作者:行者123 更新时间:2023-12-03 21:45:31 24 4
gpt4 key购买 nike

我正在尝试使用backbone.js、jasmine.js 和 sinon.js 测试按钮单击。但下面的测试用例失败了。我正在使用 spy 来跟踪它是否被调用。你能帮我解决这个问题吗?

谢谢。

新任务模板

<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>

NewTaskView

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();
});
});

Jasmine 输出

NewTaskView
runEvents
runshould #add_new_task is clicked, it should trigger the addTask method
Expected Function to have been called.

最佳答案

问题是您在主干已经将单击事件直接绑定(bind)到 addTask 函数之后添加 spy (它在 View 构建期间执行此操作)。因此你的 spy 不会被调用。

在构建 View 之前尝试将 spy 附加到 View 的原型(prototype)。像这样:

this.addTaskSpy = sinon.spy(T.views.NewViewTask.prototype, 'addTaskSpy');
this.view = new T.views.NewTaskView();

然后记得将其删除:

T.views.NewViewTask.prototype.addTaskSpy.restore()

关于javascript - 没有使用 jasmine.js 和 sinon.js 调用backbone.js 点击事件 spy ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9113186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com