angular - 如何对返回 http.patch 响应的 observable 进行单元测试?
问题描述
我是 Angular 8 单元测试的新手。我想测试一个可观察的函数,该函数在服务类中返回 http.patch 响应:
updateStatus(id: string, status: string): Observable<any> {
if (id === undefined || id === null || status === undefined || status === null) {
throw new Error('Cannot validate');
}
if (environment.role !== 'manager') {
return this.http.patch<string>(`${environment.ApiUrl}${id}/${status}`, {});
} else {
return this.http.patch<string>(`${environment.ApiUrl}${id}/${status}`, this.httpOptions);
}
}
调用 observable 的函数是:
update(pt: IPointView, status: string) {
this.isLoading = true;
this.pointsService.updateStatus(pt.id.toString(), status).subscribe(
value => {
this.context.info(pt.id, `Update the status to ${status}`, pt);
this.isLoading = false;
if (pt.ptType === this.ptTypeRode ) {
this.open(pt);
}
},
error => {
this.context.error(pt.id, `Error to update the status to ${status}`, pt);
this.isLoading = false;
}
);
}
我如何测试这个更新方法?我想覆盖这个函数内部的漏洞代码。
解决方案
我的建议是模拟该服务,因此在调用“更新”之前,您可以执行以下操作:
spyOn(yourService, 'updateStatus').and.returnValue(of("yourString"));
除了您真正控制服务器可以返回的内容之外,还有利于您的测试。
(此行必须在测试本身中,在实际调用您的“更新”状态之前......从不在生产代码中)
推荐阅读
- python - 在 conv 层上传递正确大小的神经元
- mongodb - Mongoose:如何获得 N 个随机文档,然后是另一个 N 个随机文档,没有前一批的重复
- python - 查找图中所有不存在的连接
- ios - 理解 SwiftUI 的显式对齐
- log4j2 - 启用/禁用 Log4j2 标记
- windows - 如何捕获所有触发cmd.exe在windows10上打开的命令?
- python - 根据计算标准更新 DataFrame 中的值
- acumatica - Acumatica- 参考字段数据
- java - 如何保护 Keycloak 访问令牌
- google-apps-script - 在谷歌脚本中使用谷歌表格函数