如何在Jasmine间谍上为多个调用设置不同的返回值

mik*_*ail 82 javascript unit-testing jasmine

说我在监视这样的方法:

spyOn(util, "foo").andReturn(true);
Run Code Online (Sandbox Code Playgroud)

被测功能util.foo多次调用.

是否有可能true在第一次调用间谍时返回,但false第二次返回?或者有不同的方式来解决这个问题?

Oce*_*ean 133

你可以使用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();
  });
});
Run Code Online (Sandbox Code Playgroud)

有一些事情你必须要小心,有另一个功能将类似的咒语returnValue没有s,如果你使用它,茉莉不会警告你.

  • +1:这是一个很棒的功能.但是要注意一点 - 小心不要忘记`.returnValues`中的's' - 两个函数明显不同,但是将多个参数传递给`.returnValue`不会产生错误.我不想承认由于这个角色而浪费了多少时间. (15认同)

voi*_*hos 21

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

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

  • 我们可以扩展这个超过2次调用,如下所示:var results = [true,false,"foo"]; var callCount = 0; spyOn(util,"foo").and.callFake(function(){return results [callCount ++];}); (4认同)