如何对 Jasmine 间谍的多个调用使用不同的返回值

假设我在监视这样一种方法:

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

被测试的函数多次调用 util.foo

有没有可能让间谍在第一次调用时返回 true,而在第二次调用时返回 false?还是有别的办法?

81019 次浏览

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

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

你可以使用 值返回值返回值返回值返回值返回值返回值返回值返回值返回值返回值返回值返回值返回值(比如 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没有 s,如果你使用,茉莉花将不会警告你。