【问题标题】:How can I write a unit test for an Angular5 HttpInterceptor that opens a modal?如何为打开模式的 Angular Http 拦截器编写单元测试?
【发布时间】:2018-10-14 08:51:21
【问题描述】:

我的拦截器是:

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

我想编写一个测试来检查是否打开了基于状态的适当消息的模式。

谢谢

【问题讨论】:

标签: angular unit-testing angular-http-interceptors


【解决方案1】:

我会模拟 _ngbModal 并监视 open 方法并返回一个组件实例并检查 componentInstance 上的消息键。

由于_ngbModal是第三方并且已经测试过,所以不需要对modal进行实际测试。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多