茉莉花:这是 returnValue 和 callFake 之间的唯一区别吗?

aso*_*ent 6 javascript unit-testing mocking jasmine

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

还有其他区别吗?

小智 8

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

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

组件文件:

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

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

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)
})
Run Code Online (Sandbox Code Playgroud)

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

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

组件文件:

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

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

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)
})
Run Code Online (Sandbox Code Playgroud)

component.sampleMethod(4)执行它会调用this.service.randomMethod(4)。由于randomMethod()被监视,and.callFake因此4将作为and.callFake.