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?
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.
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.
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 .
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
You can use callFake:
spyOn($cookieStore,'get').and.callFake(function(arg) { if (arg === 'someValue'){ return 'someabc'; } else if(arg === 'anotherValue') { return 'anotherabc'; } });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With