Angular interceptor testing

Published

I have such intercept method in my app with following code:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.url.split('/').includes('login')) {
      return next.handle(request);
    } else {  
      if (request.url.split('/').includes('refresh')) {
        return next.handle(request).pipe(catchError(error => {
          if (error instanceof HttpErrorResponse && error.status === 400) {  
            this.dialogRef.closeAll();
            this.router.navigate(['/login']);
          } else {
            return throwError(error);
          }
        }));
      } else {
        if (this.authService.getAccessToken()) {
          request = this.addToken(request, this.authService.getAccessToken());
        }
        return next.handle(request).pipe(catchError(error => {
          if (error instanceof HttpErrorResponse && error.status === 401) {
            return this.handle401Error(request, next, error);
          } else {
            return throwError(error);
          }
        }));
      }
    }
  }

I was trying to do like this:

fit('should redirect to login page when refresh token expired', () => {
    const request = new HttpRequest('POST', `${URL}/refresh`, 'token');
    const payload = {
      error: 'error',
      headers: new HttpHeaders(),
      status: 400,
      statusText: 'statusText',
      url: `${URL}/refresh`
    };
    const response = new HttpErrorResponse(payload);
    const next: any = {
      handle: jasmine.createSpy('handle').and.returnValue(of(response)),
    };
    interceptor.intercept(request, next).pipe(take(1)).subscribe();
    expect(dialogSpy).toHaveBeenCalled();
    expect(routerSpy.navigate).toHaveBeenCalledWith(['/login']);
  });

But this doesn`t work, looks like it cannot call catchError method, can you please help me resolve this problem?

Source: Angular Questions

Published
Categorized as angular, junit, karma-runner, testing Tagged , , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq