2

我有以下看法:

  ...
  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 abone 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 被按预期调用一次,怎么会呢?

4

1 回答 1

7

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

为了解决这个问题,您可以在初始化视图之前监视原型:

spyOn(TreeView.prototype, 'triggerFilterEvent');
var treeView = new TreeView();
于 2014-01-07T15:46:54.647 回答