【问题标题】:How can i supress Api error and return a value instead?我怎样才能抑制 Api 错误并返回一个值呢?
【发布时间】:2021-04-20 14:10:41
【问题描述】:

我从我的 API 收到未使用的 404 和已使用的电子邮件 204。现在我想使用rxjs/pipecatchError 将其转换为boolean(真/假)。

emailAvailable(): Observable<boolean> {
  return this.api.email(email).pipe(
    map((response: HttpResponse<any>) => {
      return false; // used email > false
    }),
    catchError((err: HttpErrorResponse) => {
      if (err.status === 404) {
        return of(true); // unused > true
      }
      throw err;
    })
  );
}

现在在我的单元测试中,我有这样定义的未使用电子邮件的情况

when(mockApi.email('unused@example.com')).thenThrow(
  new HttpErrorResponse({status: 404, statusText: 'E-Mail not in use', error: { message: 'E-Mail not in use'}}));

然后它尝试像这样编写我的测试。

it('should validate for unused email', async() => {
    expect(await readFirst(emailService.emailAvailable('unused@example.com'))).toBe(true);
});

现在测试失败了,因为抛出了 HttpErrorResponse

 ● EmailValidator › should validate form for unused email
    HttpErrorResponse: Http failure response for (unknown url): 404 E-Mail not in use

所以Observable 抛出了我认为我用catchError 捕获的错误。 我的测试设置是jest,我不想(也不能)切换到TestBed。

【问题讨论】:

  • 如果不是重新抛出错误,而是返回另一个 observable,比如 return EMPTY,会发生什么?
  • @AndreiGătej 我尝试捕捉 404 情况,在这种情况下我不会抛出错误,但是当使用 readFirst 监听时它仍然会抛出错误。

标签: angular rxjs ts-mockito


【解决方案1】:

这篇文章对我有帮助:

Angular 7 - catching HttpErrorResponse in unit tests

“抛出错误”路径应该在“of”中返回错误,因此它也可以测试。

模拟可以这样结束:

when(mockApi.email('unused@example.com')).thenReturn(
  throwError(new HttpErrorResponse(
    { status: 404, statusText: 'E-Mail not in use', error: { message: 'E-Mail not in use'} } 
)));

在该测试中,您可以检查您的值或该错误消息

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多