我想测试一个函数,它使用不同的参数两次调用外部 API 方法.我想用 Jasmine 间谍模拟这个外部 API,并根据参数返回不同的东西.茉莉花有没有办法做到这一点?我能想到的最好的方法是使用 andCallFake 进行破解:
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:
.andCallFake(fn).and.callFake(fn)资源:
这篇关于有什么方法可以根据参数修改 Jasmine 间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 javascript 认为文档“准备好"之前,如何让How can I get my jasmine tests fixtures to load before the javascript considers the document to be quot;readyquot;?(在 javascript 认为文档“准备好
jasmine 运行和等待实际上是做什么的?What do jasmine runs and waitsFor actually do?(jasmine 运行和等待实际上是做什么的?)
如何提供模拟文件来更改 <input type='filHow to provide mock files to change event of lt;input type=#39;file#39;gt; for unit testing(如何提供模拟文件来更改 lt;input type=filegt; 的事
如何使用 Jasmine 对链式方法进行单元测试How to unit test a chained method using Jasmine(如何使用 Jasmine 对链式方法进行单元测试)
如何将 $rootScope 注入 AngularJS 单元测试?How do I inject $rootScope into an AngularJS unit test?(如何将 $rootScope 注入 AngularJS 单元测试?)
Jasmine - 如何监视函数中的函数调用?Jasmine - How to spy on a function call within a function?(Jasmine - 如何监视函数中的函数调用?)