Aquí está el escenario:
Usar Jest/Spectator para probar RXJS observable pero parece que no puedo llegar a la línea de código que quiero probar a través de mi configuración actual
Código de componente -
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); }Prueba-
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'); });El problema que tengo es que cuando se ejecuta la prueba puedo ver que recibo un 403 pero no se llama al router.navigate. Si hago console.log esa parte del bloque de suscripción, en el componente, veo que nunca se alcanza.
¿Cómo pruebo esa línea de código?
Creo que veo tu problema.
Si usted tiene:
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); }), El return of(.. hará que vaya al bloque de éxito y no al bloque de error cuando se suscriba a esa transmisión RxJS porque catchError dice que si hay un error, manéjelo de esta manera y devuelva este ( of(.. ) para la corriente
Veo que está esperando la llamada de navegación en la parte de error de la transmisión.
Intentaría cambiar la prueba a esto:
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(); } }); });