【问题标题】:Angular - Writing unit test case for error handling methodAngular - 为错误处理方法编写单元测试用例
【发布时间】:2022-01-04 14:37:49
【问题描述】:

以下是我的服务文件中的 2 个方法

    public getStates(countryId: number) {
          let url = this.configManagerService.statesApiUrl;
          const httpHeaders = this.getHeaders();
          return this.httpClient.get(`${url}/${countryId}`, { headers: httpHeaders }).pipe(
            catchError(this.handleError)
          );
    }

    public handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError('Value list currently not available.');
    }  

我无法编写涵盖handleError 方法的单元测试用例。有人可以教育我吗?谢谢。

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    您需要使用 HttpClientTestingModule 并刷新 API 调用的错误。

    This 是一个很好的来源,但似乎他没有测试错误路线。

    查看this 以了解如何模拟 Http 调用的错误。一旦你模拟了一个错误,handleError 方法应该被调用。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2019-05-01
      • 1970-01-01
      相关资源
      最近更新 更多