eeejay
eeejay

Reputation: 5854

Jasmine spyOn with specific arguments

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?

Upvotes: 44

Views: 66470

Answers (4)

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

Upvotes: 1

Luther
Luther

Reputation: 280

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(() => {})

Upvotes: 0

Mehraban
Mehraban

Reputation: 3324

You can use callFake:

spyOn($cookieStore,'get').and.callFake(function(arg) {
    if (arg === 'someValue'){
        return 'someabc';
    } else if(arg === 'anotherValue') {
        return 'anotherabc';
    }
});

Upvotes: 56

Ismael Sarmento
Ismael Sarmento

Reputation: 894

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

Upvotes: 29

Related Questions