Reputation: 1214
Say I'm spying on a method like this:
spyOn(util, "foo").andCallFake(function() {
//some code
});
The function under test calls util.foo multiple times.
Is it possible to have the spy to call different fake functions for each next call?
The question is similar to this one: How to have different return values for multiple calls on a Jasmine spy but I need to call a function instead of returning values. If there is no native way to do so, how do I "reset" the spy to solve the problem?
Upvotes: 1
Views: 2177
Reputation: 2685
Here is how to route your spy to actually callThrough the second/subsequent times after it has been used to fake a method earlier.
I feel this illustrates what you've been trying to achieve. Fiddle to see it in action
var util = {
foo: function() {
console.log("Foo has been called")
}
}
someFunction = function() {
console.log("lets call utils foo");
util.foo();
console.log("lets call utils foo one more time");
util.foo();
console.log("lets call utils foo one last time");
util.foo();
}
describe("spec to util's foo multiple times", function() {
it('test', function() {
var self = this;
self.resetSpy = function() {
self.spyVar.and.callThrough();
};
self.spyVar = spyOn(util, 'foo').and.callFake(function(e) {
console.log("Foo hasn't been called, instead a Fake method has been called")
self.resetSpy();
});
someFunction();
expect(util.foo).toHaveBeenCalled();
});
});
Notes:
someFunction
is a function that calls util.foo
three times.callThrough
self.resetSpy
is an internal function on the spec that I invoke after the first spy call. Hope this helps.
Upvotes: 2
Reputation: 138235
Why not wrap an anonymous function around it:
var count=0;
event.on(function(){
count++;
if(count==1){
//at first
firstfunc();
}else{
//the rest
secondfunc();
}
});
Upvotes: 1