Jasmine spyOn with specific arguments

耗尽温柔 提交于 2020-07-17 09:28:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!