142

Say I'm spying on a method like this:

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

The function under test calls util.foo multiple times.

Is it possible to have the spy return true the first time it's called, but return false the second time? Or is there a different way to go about this?

2 Answers 2

238

You can use spy.and.returnValues (as Jasmine 2.4).

for example

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();
  });
});

However, there is something you must be careful about. There is another function with a similar spelling: returnValue without s. If you use that, Jasmine will not warn you, but it will behave differently.

4
  • Doing it in the beforeEach was important for me, not in the test (it)
    – Ian
    Commented Feb 14, 2019 at 11:13
  • No need to worry about spelling errors when using jasmine in TypeScript, of course. Commented Sep 28, 2019 at 19:42
  • @TheDIMMReaper that's exactly why I visit this post.... again and again, and again :D
    – Guntram
    Commented Aug 19, 2022 at 14:46
  • not working for me in [email protected]
    – vsk.rahul
    Commented Mar 28 at 4:27
32

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

var alreadyCalled = false;
spyOn(util, "foo").andCallFake(function() {
    if (alreadyCalled) return false;
    alreadyCalled = true;
    return true;
});
5
  • 5
    We can extend this for more than 2 calls like so: var results = [true, false, "foo"]; var callCount = 0; spyOn(util, "foo").and.callFake(function() { return results[callCount++]; });
    – Jack
    Commented Apr 27, 2016 at 14:21
  • 1
    This can be extended into a generic function like so: function returnValues() { var args = arguments; var callCount = 0; return function() { return args[callCount++]; }; } Commented Jul 27, 2016 at 13:41
  • 1
    Why whole this code when you can just return results.shift() ?
    – ThaFog
    Commented Oct 8, 2018 at 8:54
  • how about when we return observabvles
    – Lijo
    Commented May 20, 2019 at 10:31
  • this option is more flexible, as we can throw error or return value depending on the call order.
    – 0bj3ct
    Commented May 26, 2020 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.