我知道有一些类似的问题,但找不到一个来解决我的问题。
所以我有下面的测试(有6个期望):
it('should redirect to error page when there is a 403 error', fakeAsync(() => {
const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
error: '403 error',
status: 403,
statusText: 'Forbidden'
});
httpClient.get("/v1/test").subscribe(_ => { },
(error: HttpErrorResponse) => {
expect(error).toBeTruthy();
expect(routerSpy.navigate).toHaveBeenCalled();
expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
expect(error.status).toEqual(mockError403Response.status);
expect(error.error).toContain(mockError403Response.error);
expect(error.statusText).toContain(mockError403Response.statusText);
});
let request: TestRequest;
request = httpTestingController.expectOne("/v1/test");
request.flush(mockError403Response);
tick(500);
}));我得到了警告:
Spec 'should redirect to error page when there is a 403 error' has no expectations.对如何解决这个问题有什么建议吗?
发布于 2021-03-22 23:34:05
我在想,它永远不会出现在你订阅的错误块中。
你必须在flush中传递第二个对象作为错误响应。现在,您的测试将进入subscribe块的_ => { }。
试试这个:
it('should redirect to error page when there is a 403 error', fakeAsync(() => {
const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
error: '403 error',
status: 403,
statusText: 'Forbidden'
});
httpClient.get("/v1/test").subscribe(_ => {
// Call Jasmine fail to ensure if it comes here, the test is a failure.
// Before your test was traversing here.
fail();
},
(error: HttpErrorResponse) => {
// ensure you see this log.
console.log('!! Making assertions !!');
expect(error).toBeTruthy();
expect(routerSpy.navigate).toHaveBeenCalled();
expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
expect(error.status).toEqual(mockError403Response.status);
expect(error.error).toContain(mockError403Response.error);
expect(error.statusText).toContain(mockError403Response.statusText);
});
let request: TestRequest;
request = httpTestingController.expectOne("/v1/test");
// modify this line
request.flush(mockError403Response, { status: 403, statusText: 'Forbidden' });
tick(500);
}));请查看this,了解如何模拟Http错误。
https://stackoverflow.com/questions/66747168
复制相似问题