【问题标题】:Jasmine spyOn with specific argumentsJasmine spyOn 带有特定参数
【发布时间】:2016-08-30 08:09:05
【问题描述】:

假设我有

spyOn($cookieStore,'get').and.returnValue('abc');

这对我的用例来说太笼统了。我们随时调用

$cookieStore.get('someValue') -->  returns 'abc'
$cookieStore.get('anotherValue') -->  returns 'abc'

我想设置一个 spyOn,以便根据参数获得不同的返回:

$cookieStore.get('someValue') -->  returns 'someabc'
$cookieStore.get('anotherValue') -->  returns 'anotherabc'

有什么建议吗?

【问题讨论】:

标签: jasmine spyon


【解决方案1】:

你可以使用callFake:

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

【讨论】:

    【解决方案2】:

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

    spyOn(componentInstance, 'myFunction')
          .withArgs(myArg1).and.returnValue(myReturnObj1)
          .withArgs(myArg2).and.returnValue(myReturnObj2);
    

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

    【讨论】:

      【解决方案3】:

      实现相同结果的另一种方法是......(非常适合在不使用测试平台的情况下编写单元测试) 在根描述块中声明间谍

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

      并在构造函数中注入这个间谍来代替原始服务

      service = new StoragePage(storageServiceSpy)
      

      在 it() 块内...

      storageServiceSpy.getItem.withArgs('data').and.callFake(() => {})
      

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 1970-01-01
        • 2014-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        • 2015-08-16
        相关资源
        最近更新 更多