使用 jasmine.js 和 sinon.js 未调用backbone.js 单击事件间谍 [英] backbone.js click event spy is not getting called using jasmine.js and sinon.js

查看:23
本文介绍了使用 jasmine.js 和 sinon.js 未调用backbone.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>

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

茉莉花输出

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

推荐答案

问题是你在主干已经将点击事件直接绑定到 addTask 函数(它在视图的构建过程中这样做)之后添加你的间谍.因此你的间谍不会被召唤.

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 未调用backbone.js 单击事件间谍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆