如何对Jasmine间谍的多次调用具有不同的返回值

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

本文关键字:返回值 调用 Jasmine 间谍      更新时间:2023-09-26

假设我正在监视这样的方法:

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

被测函数多次调用util.foo

间谍第一次被调用时返回true,但第二次返回false,这可能吗?或者有其他方法可以解决这个问题吗?

您可以使用spy.and.returnValues(如Jasmine 2.4)。

例如

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

然而,有些事情你必须小心。还有另一个拼写类似的函数:returnValue without s。如果你使用它,Jasmine不会警告你,但它的行为会有所不同。

对于Jasmine的旧版本,您可以对Jasmine 1.3使用spy.andCallFake,对Jasmine2.0使用spy.and.callFake,并且您必须通过简单的闭包或对象属性等来跟踪"已调用"状态。

var alreadyCalled = false;
spyOn(util, "foo").andCallFake(function() {
    if (alreadyCalled) return false;
    alreadyCalled = true;
    return true;
});