How to have different return values ​​for multiple Jasmine spy calls

Let's say I spied on this way:

spyOn(util, "foo").andReturn(true); 

The function under testing calls util.foo several times.

Is it possible to return spy return true on the first call, but return false second time? Or is there another way to do this?

+42
javascript unit-testing jasmine
Nov 12 '14 at 23:25
source share
3 answers

You can use spy.and.returnValues ​​( like Jasmine 2.4).

eg

 describe("A spy, when configured to fake a series of return values", function() { beforeEach(function() { spyOn(util, "foo").and.returnValues(true, false); }); it("when called multiple times returns the requested values in order", function() { expect(util.foo()).toBeTruthy(); expect(util.foo()).toBeFalsy(); expect(util.foo()).toBeUndefined(); }); }); 

There is something you need to be careful about, there is another function that looks like a returnValue spell without s , if you use this, jasmine will not warn you.

+63
Feb 01 '16 at 6:26
source share

For older versions of Jasmine, you can use spy.andCallFake for Jasmine 1.3 or spy.and.callFake for Jasmine 2.0, and you will need to track the 'called' state, either through a simple closure or an object property, etc.

 var alreadyCalled = false; spyOn(util, "foo").andCallFake(function() { if (alreadyCalled) return false; alreadyCalled = true; return true; }); 
+16
Nov 12
source share

If you want to write a specification for each call, you can also use beforeAll instead of beforeEach:

 describe("A spy taking a different value in each spec", function() { beforeAll(function() { spyOn(util, "foo").and.returnValues(true, false); }); it("should be true in the first spec", function() { expect(util.foo()).toBeTruthy(); }); it("should be false in the second", function() { expect(util.foo()).toBeFalsy(); }); }); 
0
Jun 26 '17 at 17:26
source share



All Articles