aso*_*ent 6 javascript unit-testing mocking jasmine
callFake 和 returnValue 的唯一区别是 callFake 可以根据自定义逻辑(参数/环境)返回不同的值?
还有其他区别吗?
小智 8
callFake(() => {...}) 接受回调函数
- 如果我们只想要一个服务方法被调用时的返回值,那么我们可以使用任何一个
and.callFake或and.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)
在上述情况下,两种方式都是正确的。
- 假设我们将一个参数传递给 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.