【发布时间】:2018-12-04 14:52:49
【问题描述】:
我目前正在学习 Angular 7(没有使用任何以前的版本)并且在为服务编写单元测试时遇到了一些我无法修复的问题。
我有一个从 REST 获取 JSON 并将其解析为类的服务。 参考 Angular Docs,我使用 HttpClientSpy 编写了一个测试来模拟 404 错误。
会发生什么:测试失败并显示错误消息:“expected data.forEach is not a function to contain '404'”
因此,服务将 HttpErrorResponse 作为输入,但尝试将其解析为 map 函数中的常规响应。这失败了,catchError 被调用并且 data.forEach is not a function 被抛出。
预期行为:我希望 map() 没有被执行,它应该直接跳转到 catchError 函数中。
我是如何修复它的(目前):将以下代码行添加到服务的 map 函数中可以使测试工作。
if (data instanceof HttpErrorResponse)
throw new HttpErrorResponse(data);
测试:
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')
);
});
服务:
getComments(): Observable<CommentList> {
return this.http
.get('https://jsonplaceholder.typicode.com/comments')
.pipe(
map((data: Array<any>) => {
let t: Array<Comment> = [];
data.forEach(comment => {
if(!('id' in comment) || !('body' in comment) || !('email' in comment) || !('name' in comment))
throw new Error("Could not cast Object returned from REST into comment");
t.push(<Comment>{
id: comment.id,
body: comment.body,
author: comment.email,
title: comment.name,
});
});
return new CommentList(t);
}),
catchError((err: HttpErrorResponse) => {
return throwError(err);
})
);
}
我有什么问题吗?我认为预期的行为是我应该经历的,至少这就是我解释 Angular 文档的方式。
【问题讨论】:
-
您不使用
HttpClientTestingModule来测试使用HttpClient的服务有什么特别的原因吗?文档展示了如何测试错误:angular.io/guide/http#testing-for-errors。此外,您不是在嘲笑get引发错误,而是在嘲笑它解析为data = errorResponse,因此它在.forEach上窒息。
标签: angular rest http testing karma-runner