Reputation: 19812
I execute a method in the Backbone's View initialize method.
initialize : function(options) {
this.myMethod();
}
I am trying to spy on this method using sinon like:
this.spyMyMethod = sinon.spy(this.view, "myMethod");
end then
it('should call my method', function(){
expect(this.spyMyMethod).toHaveBeenCalledOnce();
});
but the test fails...
Any ideas?
Upvotes: 1
Views: 1551
Reputation: 9436
You are spying on the method too late.
Wherever you are assigning this.view
I assume it is from a call like new Views.SomeView()
. It is that new
call that will make the initialize
function be executed.
Update
I don't really recommend doing this because it is pretty messy, but you can possibly do something like the following: (I don't know sinon but this is how you would do it with the base jasmine spy objects)
it('should call my method', function(){
var dummyView = new Views.SomeView();
spyOn(dummyView, "myMethod");
spyOn(Views, "SomeView").andCallFake(function () {
dummyView.initialize();
return dummyView;
});
new Views.SomeView();
expect(dummyView.myMethod).toHaveBeenCalled();
});
Another Possiblilty
Looks like it might be possible to override that method with a spy like below. If that works, it is probably the cleanest way to do this.
it('should call my method', function(){
spyOn(Views.SomeView.prototype, "myMethod");
new Views.SomeView();
expect(Views.SomeView.prototype.myMethod).toHaveBeenCalled();
});
Upvotes: 2
Reputation: 3240
you need to return a new instance of your view for the initialize method to be called.
I'm not sure if this.view = new View(); already however
Upvotes: 0