问题
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?
回答1:
You can use callFake:
spyOn($cookieStore,'get').and.callFake(function(arg) {
if (arg === 'someValue'){
return 'someabc';
} else if(arg === 'anotherValue') {
return 'anotherabc';
}
});
回答2:
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
来源:https://stackoverflow.com/questions/37035321/jasmine-spyon-with-specific-arguments