Reputation: 47657
I'm trying to test a function call in the next scenario:
JS:
var Demo = function(option) {
if (option) func();
function func() {
console.log('called')
}
return {
'func': func
}
}
Jasmine:
beforeEach(function() {
var demo = new Demo(true);
spyOn(demo, 'func');
this.demo = demo;
});
it("should call func()", function() {
expect(this.demo.func).toHaveBeenCalled();
});
Despite it logs 'called'
in the console it fails the spec with:
Expected spy func to have been called.
From the code flow I suppose it happens because the spying begins after the function was called. So my question - what is the proper way to capture the function call in the test?
Upvotes: 0
Views: 3449
Reputation: 2636
This may be a better way to do this. Add func
as part of the Demo prototype. then you can hook up the spy to the prototype.
var Demo = function(option) {
if (option) this.func();
}
Demo.prototype.func = function(){
console.log("called")
}
beforeEach(function() {
spyOn(Demo.prototype, 'func')
var demo = new Demo(true);
this.demo = demo;
});
it("should call func()", function() {
expect(this.demo.func).toHaveBeenCalled();
});
http://jsfiddle.net/kfu7fok1/6/
Upvotes: 1