Jasmine spyOn with specific arguments
Asked Answered
B

4

42

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?

Bel answered 4/5, 2016 at 18:28 Comment(2)
Have you had a look at this question: #16198853Gpo
Possible duplicate of Any way to modify Jasmine spies based on arguments?Habitation
C
55

You can use callFake:

spyOn($cookieStore,'get').and.callFake(function(arg) {
    if (arg === 'someValue'){
        return 'someabc';
    } else if(arg === 'anotherValue') {
        return 'anotherabc';
    }
});
Carlos answered 8/7, 2016 at 10:41 Comment(0)
M
29

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

Midgut answered 16/7, 2020 at 19:29 Comment(0)
A
1

One possible solution is use the expect().toHaveBeenCalledWith() to check the parameters, example:

spyOn($cookieStore,'get').and.returnValue('abc');
$cookieStore.get('someValue') -->  returns 'abc';    

expect($cookieStore.get).toHaveBeenCalledWith('someValue');

$cookieStore.get('anotherValue') -->  returns 'abc'
expect($cookieStore.get).toHaveBeenCalledWith('anotherValue');
Antimicrobial answered 31/5, 2022 at 14:18 Comment(0)
S
0

Another way of achieving the same result would be.... (Ideal when you are writing unit tests without using a testbed) declare the spy in root describe block

const storageServiceSpy = jasmine.createSpyObj('StorageService',['getItem']);

and inject this spy in the place of original service in the constructor

service = new StoragePage(storageServiceSpy)

and inside the it() block...

storageServiceSpy.getItem.withArgs('data').and.callFake(() => {})
Shortsighted answered 22/12, 2021 at 18:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.