javascript - 仅使用特定参数返回特定值

标签 javascript unit-testing jasmine spy

在 Jasmine 中,有没有办法仅在使用特定参数调用 spy 程序时才从 spy 返回特定值?例如,我可以有这样的东西:

describe('my test', function() {
  beforeEach(function() {
    this.mySpy = jasmine.createSpy();

    // not sure how to do this, so this is pseudocode
    this.mySpy.and.returnValue(true).when.calledWith(false);
    this.mySpy.and.returnValue(false).when.calledWith(true);
  });

  it('returns true if called with false', function() {
    expect(this.mySpy(false)).toEqual(true);
  });

  it('returns false if called with true', function() {
    expect(this.mySpy(true)).toEqual(false);
  });
});

我浏览了文档,但找不到我想要的东西,并且通过搜索找不到任何相关内容。我明白为什么没有这种情况 - 你知道你在调用什么,何时,为什么,以及使用什么参数,那么为什么要制定更具体的内容呢?同时,当您可以准确指定一次想要返回的内容而不必再次指定时,这可能会导致更多代码。

最佳答案

我今天也遇到了同样的问题。我解决这个问题的方法是调用一个假方法而不是“someMethod”并处理参数以返回所需的返回值:

spyOn(SomeObj, "someMethod").and.callFake(function (property ) {
                        if (property === "someValue") {
                            return "someReturnValue";
                        } else if (property === "someOtherValue") {
                            return "someOtherReturnValue";
                        }
                    });

关于javascript - 仅使用特定参数返回特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262959/

相关文章:

java - ActivityUnitTestCase getActionBar() 返回 null

javascript - 在 jasmine 中监视 jQuery $ ('...' ) 选择器

javascript - Protractor - 失败 : stale element reference: element is not attached to the page document

javascript - 在 Gruntfile 内部或从 Gruntfile 加载和解析 .ini 文件

javascript - React Native - 从作为 prop 传递的函数调用方法

javascript - 从 win8 winrt javascript 应用程序进行 Yammer oauth 登录

api - 测试调用相同私有(private)方法的多个公共(public)方法

javascript - 如何使用jasmine测试一个需要很长时间才能响应的异步函数?

javascript - 即使在浏览器刷新后仍会继续重复的倒计时器

javascript - 成功使用 fadeIn() 和 fadeOut()