【问题标题】:jasmine: Is this the only difference between returnValue and callFake?jasmine:这是 returnValue 和 callFake 的唯一区别吗?
【发布时间】:2017-10-05 22:57:31
【问题描述】:

callFake和returnValue的唯一区别是callFake可以根据自定义逻辑(参数/环境)返回不同的值?

还有其他区别吗?

【问题讨论】:

    标签: javascript unit-testing jasmine mocking


    【解决方案1】:

    callFake(() => {...}) 接受回调函数

    1. 如果我们只想在调用服务方法时返回值,那么我们可以使用and.callFakeand.returnValue 中的任何一个

    组件文件:

    @Component(...)
    export class DependencyComponent {
      constructor(private service: RandomService){....}
      .....
      sampleMethod() {
       return this.service.randomMethod();
      }
      .....
    }
    

    上述组件的单元测试用例:

    it('test callFake vs returnValue', () => {
      let randomService= new RandomService();
      let component = new DependencyComponent(randomService);
      spyOn(randomService, 'randomMethod').and.callFake(() => 4)
      expect(component.sampleMethod()).toBe(4)
      spyOn(randomService, 'randomMethod').and.returnValue(10);
      expect(component.sampleMethod()).toBe(10)
    })
    

    在上述情况下,两种方式都是正确的。

    1. 假设我们将参数传递给服务方法以执行其逻辑,那么在这种情况下我们必须使用and.callFake((param) => {...})。这里param 参数将是传递给间谍方法的参数。

    组件文件:

    @Component(...)
    export class DependencyComponent {
      constructor(private service: RandomService){....}
      .....
      sampleMethod(val) {
      return this.service.randomMethod(val);
      }
      .....
    }
    

    上述组件的单元测试用例:

    it('test callFake vs returnValue', () => {
      let randomService= new RandomService();
      let component = new DependencyComponent(randomService);
      spyOn(randomService, 'randomMethod').and.callFake((param) => param+4)
      expect(component.sampleMethod(4)).toBe(8);
      expect(component.sampleMethod(12)).toBe(16)
    })
    

    component.sampleMethod(4) 被执行时,它会调用this.service.randomMethod(4)。由于randomMethod() 正在使用and.callFake 进行监视,因此4 将作为and.callFake 的回调函数的参数传递。

    【讨论】:

      【解决方案2】:

      callfake 有回调函数作为参数时可以看到明显的区别或好处。

      【讨论】:

        【解决方案3】:

        我在 Angular 8 代码(使用 jasmine)中观察到 returnValuecallFake 之间的奇怪行为和差异。下面是我的代码,

        spyOn(object, 'method').and.returnValue(Promise.reject('error'));
        

        当我有上面的代码时,当我调用tick() 时,上面的 spy 方法会自行调用 - 而不调用组件方法。这导致我的测试失败并出现错误Uncaught promise error。但是,当我把上面的代码改成这个时,

        spyOn(object, 'method').and.callFake(() => Promise.reject('error'));
        

        代码按预期工作,只有在组件内部调用时才会调用 spy 方法。

        无法理解这里有什么区别以及为什么callFake 有效。

        【讨论】:

        • 对于偶然发现相同问题的未来寻求者,您可能需要阅读this Github discussion,了解在处理承诺拒绝时使用callFake()returnValue。 TL;DR:在处理 Promise 拒绝时,请始终使用 callFake()
        【解决方案4】:

        两者都是一样的.. returnValue 只是我理解的 callfake 的语法糖。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-10
          • 2015-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-11
          • 2012-03-22
          • 2011-09-16
          相关资源
          最近更新 更多