有没有办法根据参数修改Jasmine间谍? [英] Any way to modify Jasmine spies based on arguments?
问题描述
我有一个函数我想测试哪个调用外部API方法两次,使用不同的参数。我想用Jasmine间谍模拟这个外部API,并根据参数返回不同的东西。在Jasmine有什么办法吗?我能想到的最好的是使用andCallFake的hack:
I have a function I'd like to test which calls an external API method twice, using different parameters. I'd like to mock this external API out with a Jasmine spy, and return different things based on the parameters. Is there any way to do this in Jasmine? The best I can come up with is a hack using andCallFake:
var functionToTest = function() {
var userName = externalApi.get('abc');
var userId = externalApi.get('123');
};
describe('my fn', function() {
it('gets user name and ID', function() {
spyOn(externalApi, 'get').andCallFake(function(myParam) {
if (myParam == 'abc') {
return 'Jane';
} else if (myParam == '123') {
return 98765;
}
});
});
});
推荐答案
在Jasmine 3.0及以上版本中,您可以使用 withArgs
In Jasmine versions 3.0 and above you can use withArgs
describe('my fn', function() {
it('gets user name and ID', function() {
spyOn(externalApi, 'get')
.withArgs('abc').and.returnValue('Jane')
.withArgs('123').and.returnValue(98765);
});
});
对于早于3.0的Jasmine版本 callFake
是正确的方法,但你可以使用一个对象来保持返回值来简化它
For Jasmine versions earlier than 3.0 callFake
is the right way to go, but you can simplify it using an object to hold the return values
describe('my fn', function() {
var params = {
'abc': 'Jane',
'123': 98765
}
it('gets user name and ID', function() {
spyOn(externalApi, 'get').and.callFake(function(myParam) {
return params[myParam]
});
});
});
根据Jasmine的版本,语法略有不同:
Depending on the version of Jasmine, the syntax is slightly different:
- 1.3.1:
.andCallFake(fn)
- 2.0:
.and.callFake(fn)
- 1.3.1:
.andCallFake(fn)
- 2.0:
.and.callFake(fn)
资源:
- withArgs docs
- callFake docs
- andCallFake vs and.callFake
这篇关于有没有办法根据参数修改Jasmine间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!