Spy on Backbone.js View Functions with Jasmine

青春壹個敷衍的年華 提交于 2020-01-15 05:48:05

问题


I'm trying to write a Jasmine spec to verify that a view's function is called when a model is added to the view's collection.

In the view's initialize function I do

this.collection.on('add', this.fooAdded, this);

In my Jasmine spec I'm doing:

describe('Foo View', function() {
   it('should call fooAdded when a Foo is added', function() {
      var view = new FooView({collection: new FooCollection()});
      spyOn(view, 'fooAdded').andCallThrough();
      view.delegateEvents();
      view.collection.add({name: 'foo'});
      expect(view.fooAdded).toHaveBeenCalled();
   });
});

My implementation of fooAdded() logs something to the console, so I know it's being called. However the spy doesn't see that the fooAdded() has been called.

See my jsFiddle


回答1:


Your problem is that spyOn replaces the spied on function with a new wrapper function but you're replacing it after the function has been used. By the time you call spyOn(view, 'fooAdded') to attach your spy, a reference to the original fooAdded is already in the collection's listener list so it is too late to spy on that callback.

If you spy on the fooAdded in the view's prototype before instantiating your view:

spyOn(FooView.prototype, 'fooAdded');
var view = new FooView(...);
view.delegateEvents();
//...

then things should work better. Demo: http://jsfiddle.net/m5Baw/1/ (thanks to amiuhle for updating the Jasmine links in the demo).

As an aside, I think something strange is going on your view, you shouldn't need to view.delegateEvents() outside the view's code so you might want to have a closer look at that.




回答2:


I was about to respond and "mu is too short" is exactly on point. First thing to prove that your spy is not getting registered is to use following code instead of yours spyOn(view, 'fooAdded').andCallThrough();

spyOn(FooView.prototype, 'fooAdded').andCallFake(function(){
           console.log('fake "fooAdded" called');
        });

This will never be called as fooAdded is already registered with collection listener. Here is the updated jsFiddle



来源:https://stackoverflow.com/questions/14056720/spy-on-backbone-js-view-functions-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!