angular - 带有 retryWhen 的 rxjs 单元测试
问题描述
我有以下方法,我需要为它编写一些单元测试,但我无法模拟响应,我尝试使用 TestScheduler 但它没有成功,任何帮助将不胜感激。我在开玩笑。
protected waitForResponse(id: number, requestId: string) {
return this.service.getData(id, requestId)
.pipe(
mergeMap((resp: ResponseModel) => {
if (resp.status !== 'WAITING') {
return of(resp);
}
return throwError(resp);
}),
retryWhen(errors => errors.pipe(
concatMap((e, i) =>
iif(
() => i > 11,
// max number of 11 attempts has been reached
throwError(new HttpErrorResponse({status: HttpStatusCode.TOO_MANY_REQUESTS})),
// Otherwise try again in 5 secs
of(e).pipe(delay(5000))
)
)
)
)
);
}
解决方案
我设法通过使用以下功能获得了解决方案:
const mockFunction = (times) => {
let count = 0;
return Observable.create((observer) => {
if (count++ > times) {
observer.next(latestData);
} else {
observer.next(waitingData);
}
});
};
我用 jest spy 来模拟返回值:
jest.spyOn(service, 'getData').mockReturnValue(mockFunction(4));
这将返回 4 个等待响应,它们是最新的一个。
jest.spyOn(service, 'getData').mockReturnValue(mockFunction(20));
任何超过 11 的数字都将导致超过我的最大尝试次数
推荐阅读
- c# - 加入项目列表
- php - 尝试在托管在 aws 上的 laravel 应用程序上提交注册表时,我不断收到服务器错误 500
- c++ - 我的代码检查问题 CIELAB 解决方案有什么问题
- ruby-on-rails - 属于项目时无法创建新接口
- matrix - 遍历和操作 Sympy 矩阵
- angular - 如何不从ngrx商店获取空值
- c - 后缀计算器中第二个堆栈的难题
- python - 指定要在 Seaborn pairplot 中绘制的数据
- javascript - How to use jQuery in WordPress shortcode?
- javascript - Uncheck checkbox when certain values(php) from drop down is chosen