Javascript 如何为 Jasmine 间谍的多次调用提供不同的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26898613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:29:29  来源:igfitidea点击:

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

javascriptunit-testingjasmine

提问by mikhail

Say I'm spying on a method like this:

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

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

The function under test calls util.foomultiple times.

被测函数util.foo多次调用。

Is it possible to have the spy return truethe first time it's called, but return falsethe second time? Or is there a different way to go about this?

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

回答by Ocean

You can use spy.and.returnValues(as Jasmine 2.4).

您可以使用spy.and.returnValues(如 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 returnValuewithout s, if you use that, jasmine will not warn you.

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

回答by voithos

For older versions of Jasmine, you can use spy.andCallFakefor Jasmine 1.3 or spy.and.callFakefor Jasmine 2.0, and you'll have to keep track of the 'called' state, either through a simple closure, or object property, etc.

对于较旧版本的 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;
});

回答by Dabrule

If you wish to write a spec for each call you can also use beforeAll instead of beforeEach :

如果您想为每个调用编写规范,您还可以使用 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();
  });
});