问题
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