angular - Angular - 如何测试应该被召回的服务,直到它回复OK?
问题描述
我有一个维护页面,应该在运行状况检查 API 回复正常后重定向到登录页面。
我的问题是:我想测试模拟 2 个调用:
- 第一次调用会返回错误
- 第二个将返回成功(允许调用转到下一页)
. 但我不知道如何测试它是否this.$state.go
在每次调用后单独调用了该方法。
一个例子:StackBlitz。
我的实现:(重要的部分)
ngOnInit() {
const retries = interval(30000);
//First check
this.recheck();
this.subscriptionInterval = retries.subscribe(() => {
this.recheck();
});
}
private recheck(): void {
this.httpClient.get('/health-check').subscribe(
() => {
//In case of success, go to login
this.subscriptionInterval.unsubscribe();
this.$state.go('auth.login');
}, () => {
// otherwise, keep retrying.
});
}
整个文件:https ://stackblitz.com/edit/angular-ivy-plw32n?file=src%2Fapp%2Fapp.component.ts
我的测试:
it('should keep retrying if is receiving errors', fakeAsync(() => {
expect(component).toBeTruthy();
tick(component.RETRIES_AFTER_MS);
fixture.detectChanges();
const requests = httpTestingController.match('/elb_health_check');
expect(requests.length).toBe(2)
// Respond to each request with different results
requests[0].flush({}, { status: 500, statusText: 'INTERNAL ERROR' });
requests[1].flush({}, { status: 200, statusText: 'OK' });
// How to test that in first call it has not called the mockGo, but in the seconds has done it?
expect(mockGo).toHaveBeenCalledTimes(0);
expect(mockGo).not.toHaveBeenCalledWith('auth.login');
component.subscriptionInterval.unsubscribe();
flush();
}));
它的一个例子:https : //stackblitz.com/edit/angular-ivy-plw32n?file=src%2Fapp%2Fapp.component.spec.ts(它不起作用,Stackblitz 不识别茉莉花)
我已经看到我们应该使用 tick 来模拟时间。但是在mock最后来的HttpClientTestModule的这个结构中,我不知道该怎么做。
解决方案
推荐阅读
- vba - 如何绕过使用 Application.SendKeys 破坏 InternetExplorer 对象
- javascript - 如何使用 vanilla JS 制作自定义动画增长饼图
- node.js - 从 Angular 到 Express 服务器的 http post 请求导致 404 错误
- c++ - 成员变量如何与专门的类模板一起工作?
- c# - C# DllImport 调用非托管 C++ 函数回调
- javascript - 如何在 axios get 请求中返回值?
- angular - Angular KendoGrid 未通过 @Input 变量将值传递给子网格
- android - Android如何在视图中绘制形状居中
- maven - 未指定模块时 Maven 插件崩溃
- python - TypeError:无法比较类型 'ndarray(dtype=bool)' 和 'str'