Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine spyOn with specific arguments

Tags:

jasmine

spyon

Suppose I have

spyOn($cookieStore,'get').and.returnValue('abc'); 

This is too general for my use case. Anytime we call

$cookieStore.get('someValue') -->  returns 'abc' $cookieStore.get('anotherValue') -->  returns 'abc' 

I want to setup a spyOn so I get different returns based on the argument:

$cookieStore.get('someValue') -->  returns 'someabc' $cookieStore.get('anotherValue') -->  returns 'anotherabc' 

Any suggestions?

like image 868
eeejay Avatar asked May 04 '16 18:05

eeejay


People also ask

How do you pass arguments in spyOn?

spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.

How do you spyOn a method in Jasmine?

There are two ways to create a spy in Jasmine: spyOn() can only be used when the method already exists on the object, whereas jasmine. createSpy() will return a brand new function: //spyOn(object, methodName) where object. method() is a function spyOn(obj, 'myMethod') //jasmine.

How do you spy on a variable in Jasmine?

so to spy on getters/setters you use: const spy = spyOnProperty(myObj, 'myGetterName', 'get'); where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {} and the third param is the type get or set .

What is spyOn in Jasmine angular?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.


2 Answers

You can use callFake:

spyOn($cookieStore,'get').and.callFake(function(arg) {     if (arg === 'someValue'){         return 'someabc';     } else if(arg === 'anotherValue') {         return 'anotherabc';     } }); 
like image 50
Mehraban Avatar answered Sep 23 '22 04:09

Mehraban


To the ones using versions 3 and above of jasmine, you can achieve this by using a syntax similar to sinon stubs:

spyOn(componentInstance, 'myFunction')       .withArgs(myArg1).and.returnValue(myReturnObj1)       .withArgs(myArg2).and.returnValue(myReturnObj2); 

details in: https://jasmine.github.io/api/edge/Spy#withArgs

like image 37
Ismael Sarmento Avatar answered Sep 20 '22 04:09

Ismael Sarmento