這是場景:
使用 Jest/Spectator 測驗可觀察的 RXJS,但似乎無法通過當前設定進入我想要測驗的代碼行
組件代碼 -
ngOnInit(): void {
this.authDetail$ = this.validateToken(this.token).pipe(
takeUntil(this.unsubscribe$),
catchError((error) => {
if (error) {
// I want to test this next line...
// But I never see it run...
this.router.navigate(['unauthorized'], { replaceUrl: true });
}
// This only exists to satisfy the observable chain.
return of({} as SomeModel);
}),
);
}
validateToken(token: string): Observable<SomeModel> {
return this.authService.lookupByToken(token);
}
測驗-
it('should redirect to "unauthorized" when error is thrown', (done) => {
jest.spyOn(spectator.component, 'validateToken')
.mockReturnValue(throwError({ status: 403 }) as any);
spectator.component.validateToken('invalid_token').subscribe({
next: (data) => {
console.log('NEXT BLOCK: Should Have Thrown Error');
done();
},
error: (error) => {
expect(spectator.router.navigate).toHaveBeenCalledWith(
['unauthorized'],
{ replaceUrl: true },
);
expect(error).toBeTruthy();
done();
},
});
// This fires off the ngOnInit :)
spectator.setRouteParam('token', 'INVALID_TOKEN');
});
我遇到的問題是,當測驗運行時,我可以看到我收到了 403,但沒有呼叫 router.navigate。如果我在組件中 console.log 訂閱塊的那一部分,我會看到它從未到達過。
我如何測驗那行代碼?
uj5u.com熱心網友回復:
我想我看到了你的問題。
如果你有:
catchError((error) => {
if (error) {
// I want to test this next line...
// But I never see it run...
this.router.navigate(['unauthorized'], { replaceUrl: true });
}
// This only exists to satisfy the observable chain.
return of({} as SomeModel);
}),
當return of(..您訂閱該 RxJS 流時,它將使其進入成功塊而不是錯誤塊,因為catchError如果有錯誤,則以這種方式處理它并of(..為流回傳 this ()。
我看到您在流的錯誤部分期待導航呼叫。
我會嘗試將測驗更改為:
it('should redirect to "unauthorized" when error is thrown', (done) => {
jest.spyOn(spectator.component, 'validateToken')
.mockReturnValue(throwError({ status: 403 }) as any);
// This fires off the ngOnInit :)
spectator.setRouteParam('token', 'INVALID_TOKEN');
// subscribe to authDetail$ after it has been defined in ngOnInit
spectator.component.authDetail$.pipe(take(1)).subscribe({
next: (result) => {
expect(spectator.router.navigate).toHaveBeenCalledWith(
['unauthorized'],
{ replaceUrl: true },
);
expect(result).toBeTruthy();
done();
}
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421466.html
標籤:
上一篇:如何模擬django模型物件?
