Monday, June 3, 2024
59
rated 0 times [  62] [ 3]  / answers: 1 / hits: 138416  / 11 Years ago, wed, april 24, 2013, 12:00:00

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

More From » unit-testing

 Answers
23

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


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


Depending on the version of Jasmine, the syntax is slightly different:




  • 1.3.1: .andCallFake(fn)

  • 2.0: .and.callFake(fn)



Resources:




[#78650] Tuesday, April 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;