MethodToBeTested() {
this.serviceA.methodA1().subscribe((response) => {
if (response.Success) {
this.serviceA.methodA2().subscribe((res) => {
this.serviceB.methodB1();
})
}
});
}
这是场景。
要测试的内容:
serviceA.methodA1().
被调用。- 如果response.Success,则检查是否调用了
serviceA.methodA2()
- 检查
serviceB.methodB1()
在serviceA.methodA2()
收到值时是否被调用。
第一,易于测试。
let spy = spyOn(serviceA, 'methodA1');
expect(spy).toHaveBeenCalled();
但是测试 2 和 3 吗?
let spy= spyOn(serviceA, 'methodA1').and.returnValue({subscribe: () => {success:true}});
subject.MethodToBeTested();
类似的东西?
最佳答案
好吧,所以我发现我要找的是callFake
it('should test inside of subscribe', () => {
let spy = spyOn(serviceA, 'methodA1').and.callFake(() => {
return of({ success: true });
});
let spy2 = spyOn(serviceA, 'methodA2').and.callFake(() => {
return of({ success: true });
});
let spy3 = spyOn(serviceB, 'methodB1').and.returnValue(of({ success: true }));
subject.MethodToBeTested();
expect(spy3).toHaveBeenCalled();
});
我了解到 returnValue
不会实际执行订阅内部,而 callFake
将使用您在其中提供的数据。
关于javascript - 如何在 Angular 中对嵌套订阅方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940614/