[英]How to unit test nested subscribe methods in Angular?
MethodToBeTested() {
this.serviceA.methodA1().subscribe((response) => {
if (response.Success) {
this.serviceA.methodA2().subscribe((res) => {
this.serviceB.methodB1();
})
}
});
}
這是場景。
要測試的東西:
serviceA.methodA1().
被稱為。 serviceA.methodA2()
serviceA.methodA2()
收到值時是否調用了serviceB.methodB1()
。 首先,一個很容易測試。
let spy = spyOn(serviceA, 'methodA1');
expect(spy).toHaveBeenCalled();
但是一個測試2和3嗎?
let spy= spyOn(serviceA, 'methodA1').and.returnValue({subscribe: () => {success:true}});
subject.MethodToBeTested();
這樣的東西?
最好不要使用嵌套訂閱。
這樣的事情可能是解決方案:
let $obs1 = this.serviceA.methodA1().pipe(share());
let $obs2 = $obs1.pipe(switchMap(x => this.serviceA.methodA2()));
$obs1.subsribe(logic1 here...);
$obs2.subsribe(logic2 here...);
好了,所以我知道我要尋找的是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
將使用您在訂閱內部提供的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.