我正在尝试使用 HttpTestingController 刷新带有 http 400 错误的响应。然而,它似乎永远不会被刷新,因为订阅的委托永远不会被调用。
记录请求对象的 _cancelled 属性表明返回 400 的 http 错误导致 _cancelled 属性设置为 true。我希望将错误响应传递给服务方法,以便可以测试它对 http 错误代码的处理。
考试:
it('routes to error page when get roles receives an error', async(inject(
[AgentManagementService, HttpTestingController],
(service: AgentManagementService, backend: HttpTestingController) => {
service.GetAgentPortalRoles().subscribe( (response) => {
console.log(response); // never gets called
expect(1).toBe(1);
});
const request = backend.expectOne(environment.urlBase + 'v1/account/roles');
expect(request.cancelled).toBeFalsy();
console.log(request.cancelled); // is true
request.flush( {}, { status: 400, statusText: 'Bad Request'});
console.log(request.cancelled); // is false
}
)));
正在测试的服务中的功能:
public GetAgentPortalRoles(): Observable<Array<string>> {
return this.http.get<RolesResponse>(API_URL + 'v1/account/roles', { observe: 'response', headers })
.pipe(
map( response => {
if (response.ok) {
return response.body.roles;
}
this.router.navigateByUrl('/error');
return null;
}),
catchError( () => {
this.router.navigateByUrl('/error');
return EMPTY;
})
);
}