仅使用某些参数返回某些值

时间:2015-03-25 17:51:18

标签: javascript unit-testing jasmine spy

在Jasmine中,只有在使用某些参数调用时才有从间谍返回某个值的方法吗?例如,我可以使用:

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);
  });
});

我查看了文档,但找不到我想要的内容,也无法通过搜索找到任何相关内容。我可以看出为什么不存在这样的情况 - 你知道你在调用什么,何时,为什么,以及用什么参数,为什么要更具体?同时,当您可以准确指定要返回的内容时,这可能会产生更多代码,而不必再次指定它。

1 个答案:

答案 0 :(得分:1)

我今天遇到了同样的问题。我修复它的方法是调用假方法而不是" someMethod"并处理params以返回所需的返回值:

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