Jasmine spyOn有特定的论点

eee*_*jay 19 jasmine spyon

假设我有

spyOn($cookieStore,'get').and.returnValue('abc');
Run Code Online (Sandbox Code Playgroud)

这对我的用例来说太笼统了.我们随时打电话

$cookieStore.get('someValue') -->  returns 'abc'
$cookieStore.get('anotherValue') -->  returns 'abc'
Run Code Online (Sandbox Code Playgroud)

我想设置一个spyOn,所以我根据参数得到不同的回报:

$cookieStore.get('someValue') -->  returns 'someabc'
$cookieStore.get('anotherValue') -->  returns 'anotherabc'
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Meh*_*ban 28

你可以使用callFake:

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


Ism*_*nto 11

对于使用 jasmine 3 及以上版本的用户,您可以使用类似于 sinon 存根的语法来实现这一点:

spyOn(componentInstance, 'myFunction')
      .withArgs(myArg1).and.returnValue(myReturnObj1)
      .withArgs(myArg2).and.returnValue(myReturnObj2);
Run Code Online (Sandbox Code Playgroud)

详情见:https : //jasmine.github.io/api/edge/Spy#withArgs