使用Jasmine监视Backbone View回调方法

时间:2014-01-07 14:49:43

标签: backbone.js view jasmine spy

我有以下观点:

  ...
  var TreeView = Backbone.View.extend({
    el: '#org-tree',

    initialize: function() {
      eventBus.on("route:change", _.bind(this.triggerFilterEvent, this));
    },

    render: function() { ... },

    foo: function() { console.log("foo"); },

    triggerFilterEvent: function(name) {
      this.foo();
      ...
    }

  });
  ...

我的规格如下:

 describe('TreeView', function() {
    var treeView = new TreeView();

    it('calls triggerFilterEvent when receiving a route:change', function() {
      spyOn(treeView, 'triggerFilterEvent');
      spyOn(treeView, 'foo');
      treeView.delegateEvents();
      eventBus.trigger("route:change", "test");
      console.log('TriggerCOunt:' + treeView.triggerFilterEvent.callCount);
      console.log('FooCount: ' + treeView.foo.callCount);
      expect(treeView.triggerFilterEvent).toHaveBeenCalled();
    });
  });

我按照以下解决方案中的建议添加了treeView.delegateEvents()SpyOn a backbone view method using jasmine

但是我的测试仍然失败了:

LOG: 'triggerFilterEvent with: test'
LOG: 'Event has been triggered: route:change'
LOG: 'TriggerCOunt:0'
LOG: 'FooCount: 1'
Error: Expected spy triggerFilterEvent to have been called.

方法foo按预期调用一次,但是为什么会这样?

1 个答案:

答案 0 :(得分:6)

问题是在triggerFilterEvent上分配间谍时,事件监听器已设置为调用原始函数而不是间谍(初始化视图时调用initialize)< / p>

要解决这个问题,你可以监视原型,之前初始化视图:

spyOn(TreeView.prototype, 'triggerFilterEvent');
var treeView = new TreeView();