在 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/