Search code examples
angularunit-testingangular-http-interceptors

How can I write a unit test for an Angular5 HttpInterceptor that opens a modal?


My interceptor is:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private _ngbModal: NgbModal) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
    .catch((err) => {
      let componentInstance = this._ngbModal.open(ErrormodalComponent, {size: 'sm', backdrop: 'static' }).componentInstance

      switch(err.status) {
        case 401:
          componentInstance["message"] = "User session lost, please logout and log back in."
          break;
        case 404:
          componentInstance["message"] = "API Route Not found"
          break;
        default:
          componentInstance["message"] = "API Currently Unavailable. Please try again."
          break;


      }
      return Observable.throw(err);
    })
  }
}

And I want to write a test that checks to see that the modal was opened with the appropriate messages based on status.

Thank you


Solution

  • I would have mocked _ngbModal and spyed on open method and returned a component instance and checked the message key on componentInstance.

    Since _ngbModal is a third party and already tested, there is ni need to actually test the modal.

    Hope this helps.