Any way to modify Jasmine spies based on arguments?

I have a function that I would like to test that calls the external API twice using different parameters. I would like to make fun of this external API with a Jasmine spy and return different things based on parameters. Is there any way to do this in Jasmine? The best I can come up with is 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; } }); }); }); 
+80
javascript unit-testing jasmine
Apr 24 '13 at 17:22
source share
2 answers

callFake is the right way, but you can simplify it by using an object to store 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] }); }); }); 

The syntax is slightly different depending on the version of Jasmine:

  • 1.3.1: .andCallFake(fn)
  • 2.0: .and.callFake(fn)

Resources:

+109
Apr 25 '13 at 6:45
source share

You can also use $provide to create a spy. And a layout using and.returnValues instead of and.returnValue to pass parameterized data.

According to Jasmine docs:. and.returnValues spy with and.returnValues , all function calls return certain values ​​until they reach the end of the list of return values, after which it returns undefined for all subsequent calls.

 describe('my fn', () => { beforeEach(module($provide => { $provide.value('externalApi', jasmine.createSpyObj('externalApi', ['get'])); })); it('get userName and Id', inject((externalApi) => { // Given externalApi.get.and.returnValues('abc','123'); // When //insert your condition // Then // insert the expectation })); }); 
+3
Nov 15 '16 at 6:17
source share



All Articles