Olena Horal
Olena Horal

Reputation: 1214

How to have different fake functions called for multiple calls on a Jasmine spy

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

Answers (2)

Winter Soldier
Winter Soldier

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.
  • Say you'd want to fake it once but the next two calls you want to actually call the function itself, then we can initially set the spy to use a fake method however for the second and third calls, we reset teh spy to actually callThrough
  • self.resetSpy is an internal function on the spec that I invoke after the first spy call.
  • more info on reset the spy is here

Hope this helps.

Upvotes: 2

Jonas Wilms
Jonas Wilms

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

Related Questions