小编Mar*_*ehl的帖子

Angular 7 - 在单元测试中捕获 HttpErrorResponse

我目前正在学习 Angular 7(没有使用过任何以前的版本)并且在为服务编写单元测试时遇到了我无法修复的问题。

我有一个从 REST 获取 JSON 并将其解析为一个类的服务。参考 Angular Docs,我使用 HttpClientSpy 编写了一个测试来模拟 404 错误。

发生了什么:测试失败并显示错误消息:“预期的 data.forEach 不是包含‘404’的函数”

因此,服务获取 HttpErrorResponse 作为输入,但尝试将其解析为 map 函数中的常规响应。这失败了, catchError 被调用并且 data.forEach is not a function Error 被抛出。

预期行为:我希望 map() 不会被执行,它应该直接跳到 catchError 函数中。

我是如何修复它的(目前):将以下代码行添加到服务的地图功能使测试工作。

if (data instanceof HttpErrorResponse)
      throw new HttpErrorResponse(data);
Run Code Online (Sandbox Code Playgroud)

考试:

it('should throw an error when 404', () => {

const errorResponse = new HttpErrorResponse({
  error: '404 error',
  status: 404, statusText: 'Not Found'
});

httpClientSpy.get.and.returnValue(of(errorResponse));

service.getComments().subscribe(
  fail,
  error => expect(error.message).toContain('404')
);
});
Run Code Online (Sandbox Code Playgroud)

服务: …

testing rest http karma-runner angular

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

angular ×1

http ×1

karma-runner ×1

rest ×1

testing ×1