如何在Jasmine间谍上多次调用不同的返回值

说我正在监视这样一个方法:

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

被testing的函数多次调用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(); }); }); 

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

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

如果你想为每个调用写一个规范,你也可以使用beforeAll而不是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(); }); });