【发布时间】:2020-01-08 08:31:24
【问题描述】:
假设一个组件方法创建一个 HTTP GET 请求,在等待响应时设置加载状态,并在给出响应时移除加载状态。例如:
getData() {
this.myService
.getSomeDate()
.pipe(tap(_ => {
this.loading = true;
}))
.subscribe(result => {
this.data = result;
this.loading = false;
});
}
您将如何通过测试验证请求和响应之间的状态(例如pipe 部分)是否确实正在加载?我尝试使用HttpTestingController 发送HttpEventType.Sent 事件,但似乎不起作用。调用req.flush() 将导致代码立即转到subscribe 部分,这样也不起作用。这是我用过的测试方法:
it('should have a loading state durin the request', () => {
component.getData();
const req = httpClient.expectOne('http://localhost:8080');
req.event({type: HttpEventType.Sent});
expect(component.loading).toBe(true);
req.flush();
expect(component.loading).toBe(false);
});
【问题讨论】: