How to have different return values for multiple c

2019-02-07 16:25发布

问题:

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

There is some thing you must be careful about, there is another function will similar spell returnValue without s, if you use that, jasmine will not warn you.



回答2:

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


回答3:

If you wish to write a spec 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();
  });
});