20

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

谢谢。

新任务模板

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

3 回答 3

41

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

在构建视图之前尝试将间谍附加到视图的原型。像这样:

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

然后记得删除它:

T.views.NewViewTask.prototype.addTaskSpy.restore()
于 2012-04-24T16:20:37.950 回答
0

您的方法存在一些问题。首先,您监视要测试的类,这不是单元测试应该工作的方式,因为您测试的是类的内部逻辑而不是其行为。其次,这就是您的测试失败的原因,您没有将视图 el 附加到 DOM 中。因此,要么将 el 附加到 DOM,要么将 click 事件直接触发到 el: $('#add_new_task', this.view.el).click()

顺便提一句。创建元素和绑定事件的主干方式使得编写好的单元测试变得困难,因为你不得不使用 DOM 和 jquery。编写可测试代码的更好方法是始终将所有依赖项传递给构造函数,并且不要在代码中创建新实例,因为这会导致难以测试这些对象。因此,在您的情况下,将 el 对象作为 jquery 对象注入构造函数中并手动注入事件会容易得多。这样做你可以测试你的类而不依赖于 DOM 或 jquery。

因此,在您的情况下,构造函数将如下所示:

initialize: function(){
   this.el.click(_.bind( this, 'addTask'));
}

你的测试:

var el = {click: function(){}};
spyOn( el, 'click');
new T.views.NewTaskView({el: el});
expect(el.click).toHaveBeenCalled(); //test the click event was bind
//call the function that was bind to the click event, 
//which is the same as trigger the event on a real DOM object
el.click.mostRecentCall.args[0]() 

毕竟,您必须决定哪种方法适合您的需求。带有主干助手的更精简的代码或对 jquery、DOM 和主干的依赖更少的更好的可测试代码。

于 2012-02-03T10:24:34.510 回答
0
events:{
    "click" : "addTask"
},

意味着您将单击事件绑定到this.el视图的 - 根元素,在您的情况下,该元素具有 ID new_task_section。您需要将它绑定到#add_new_task我假设的“添加任务”按钮 - 这应该可以解决它!

events:{
    "click #add_new_task" : "addTask"
},

更新:

$("#add_new_task") 不会找到元素,因为视图没有添加到文档 DOM 树中。使用this.view.$('#add_new_task')它应该可以工作,因为它将搜索存储在视图中的分离片段中的元素。

于 2012-02-03T02:44:19.880 回答