Reputation: 5088
I'm trying to spy on a Backbone view. Within one of the view function, an object is created and attached to the view:
var BackboneView = Backbone.View.extend({
anObject: null,
.....
viewFunction: function() {
if (!this.anObject) {
this.anObject = new theObject();
this.anObject.setTimeout(10);
}
}),
....
});
return BackboneView;
The object looks like this (and cannot be changed):
var theObject = function () {
this.setTimeout = function (timeout) {
//set timeout
};
return this;
});
return theObject;
I want to make sure setTimeout was called. So I tried:
it('theObject.prototype.setTimeout called', function () {
spyOn(theObject.prototype, 'setTimeout');
myBackboneView.viewFunction()
expect(theObject.prototype.setTimeout).toHaveBeenCalled();
});
But I get the error:
setTimeout() method does not exist
So I try to spy on it through the Backbone view:
it('myBackboneView.anObject.setTimeout called', function () {
spyOn(myBackboneView.anObject, 'setTimeout');
myBackboneView.viewFunction();
expect(myBackboneView.anObject.setTimeout).toHaveBeenCalled();
});
But I predictably get the error:
spyOn could not find an object to spy upon for setTimeout()
Any ideas how I make sure setTimeout() was called?
Upvotes: 0
Views: 103
Reputation: 20155
setTimeout() method does not exist
Because you did not set setTimeout on the function prototype.
if you want a function on a prototype you need to put it on a prototype,then you can spy on the function.
theObject.prototype.setTimeout=function(){/*some code*/}
and no need to return this in the constructor.
this.setTimeout = function (timeout) {
//set timeout
};
return this; // this is wrong!!!
Upvotes: 1