jeudi 24 octobre 2019

How do I test HttpInterceptor with Routing for Angular?

I am using Angular 8.

I am trying to a unit test on the HttpInterceptor and redirect to an error page when it received a fatal error.

How do I proceed with my test? Do i just do a test on errorHandler method itself? Or do i need to trigger it from the request point of view?

error-handler.interceptor.ts:

export class ErrorHandlerInterceptor implements HttpInterceptor {
  log: Logger;

  constructor(private noti: NotificationCenterService, private router: Router, private http: HttpClient) {
    this.log = new Logger(http, 'ErrorHandlerInterceptor');
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(error => this.errorHandler(error)));
  }

  // Customize the default error handler here if needed
  private errorHandler(error: HttpErrorResponse): Observable<HttpEvent<any>> {
    const errorMsg = error.error.message || error.error || error.statusText;

    if (error.status === undefined || error.status === null || error.status === 500 || error.status === 0) {
      //redirect to error page
      this.router.navigate(['fatalerror']);
    } else {
      //show in notification
      this.noti.open(errorMsg, 'OK');
    }

    this.log.info("ErrorHandlerInterceptor - Error not caught!");

    throw error;
  }
}

app-routing.modules:

...
const routes: Routes = [
  Shell.childRoutes([{ path: 'fatalerror', loadChildren: './shared/fatalerror/fatalerror.module#FatalerrorModule' }]),
  { path: '**', redirectTo: '', pathMatch: 'full' }
];
...

error-handling.interceptor.spec.ts:

import { Type } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

import { ErrorHandlerInterceptor } from './error-handler.interceptor';
import { NotificationCenterService } from '@app/shared/notification-center.service';

describe('ErrorHandlerInterceptor', () => {
  let errorHandlerInterceptor: ErrorHandlerInterceptor;
  let http: HttpClient;
  let httpMock: HttpTestingController;
  let noti: jasmine.SpyObj<NotificationCenterService>;
  let router: Router;

  function createInterceptor() {
    errorHandlerInterceptor = new ErrorHandlerInterceptor(noti, router, http);
    return errorHandlerInterceptor;
  }

  beforeEach(() => {
    const spy = jasmine.createSpyObj('NotificationCenterService', ['open']);

    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule.withRoutes(routes)],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useFactory: createInterceptor,
          multi: true
        },
        {
          provide: NotificationCenterService,
          useValue: spy
        }
      ]
    });
    noti = TestBed.get(NotificationCenterService);
    http = TestBed.get(HttpClient);
    httpMock = TestBed.get(HttpTestingController as Type<HttpTestingController>);
    router = TestBed.get(Router);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should redirect to fatal error page upon fatal error', () => {

    spyOn(ErrorHandlerInterceptor.prototype as any, 'errorHandler').and.callThrough();

    //how to proceed
  });
});

Aucun commentaire:

Enregistrer un commentaire