How to have different return values for multiple calls on a Jasmine spy Ask Question

How to have different return values for multiple calls on a Jasmine spy Ask Question

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?

ベストアンサー1

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.

おすすめ記事