如何在Jasmine间谍上为多个调用设置不同的返回值 [英] How to have different return values for multiple calls on a Jasmine spy

查看:104
本文介绍了如何在Jasmine间谍上为多个调用设置不同的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在监视这样的方法:

Say I'm spying on a method like this:

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

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

The function under test calls util.foo multiple times.

第一次调用时,是否有可能让间谍返回为真,但返回 false 第二次?或者有不同的方法可以解决这个问题吗?

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

推荐答案

你可以使用spy.and.returnValues (作为Jasmine 2.4)。

You can use spy.and.returnValues (as 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 ,如果你使用它,jasmine不会警告你。

There is some thing you must be careful about, there is another function will similar spell returnValue without s, if you use that, jasmine will not warn you.

这篇关于如何在Jasmine间谍上为多个调用设置不同的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆