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

标签 javascript jquery backbone.js jasmine sinon

我正在尝试使用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/

相关文章:

javascript - 如何在 ASP.Net MVC 4 中为日期选择器添加 javascript

javascript - 缩短或简化 jQuery 逻辑

javascript - 尝试使用 jQuery 检索部分 URL;它有效,但未返回字符串

javascript - 在expressJs中堆栈jquery

javascript - WebView中的js函数window.innerHeight只返回0?

javascript - 使用 jquery 重新定位 html 中的元素

Jquery移动: Forcing refresh of content

javascript - Node.js 服务器将数据发送到 Backbone 模型

javascript - Backbone.js 模型数据检索