没有使用 jasmine.js 和 sinon.js 调用主干.js 点击事件间谍

时间:2023-02-15
本文介绍了没有使用 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 期望逻辑(期望 A OR B) 下一篇:如何为 Jasmine 间谍的多个调用提供不同的返回值

相关文章

最新文章