如何为打开模态的Angular5 HttpInterceptor编写单元测试?

我的拦截器是:

@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);
    })
  }
}

我想编写一个测试,检查模式是否已根据状态使用适当的消息打开.

谢谢

最佳答案 我会嘲笑_ngbModal并使用open方法并返回一个组件实例并检查componentInstance上的消息键.

由于_ngbModal是第三方并已经过测试,因此需要实际测试模态.

希望这可以帮助.

点赞