我有一个组件,最终通过连续的 switchMap
调用一堆 HTTP 服务以从后端获取数据。
我想测试错误处理部分。该应用程序具有全局错误处理 (ErrorHandler) 和通过 catchError 进行的本地错误处理。
测试方法如下:
public methodUsingObservable() {
this.someRequest()
.pipe(catchError((error) => this.handleError(error)))
.subscribe(console.log);
}
处理错误,检查错误是否链接到业务操作,并再次抛出它以由全局处理程序处理
handleError(error) {
checkLocally(error);
return throwError(error);
}
对于我的测试,我使用 throwError
模拟 someRequest
来模拟后端调用的问题
it('should handle the error when one occurs', fakeAsync(() => {
const service: MachinService = TestBed.get(MachinService);
spyOn(service,'someRequest').and.returnValue(throwError(new Error("Failing HTTP call")));
spyOn(service,'handleError').and.callThrough();
service.methodUsingObservable();
tick();
expect(service.methodUsingObservable).toThrowError();
expect(service.handleError).toHaveBeenCalled();
}));
但是,无论我如何监视和期望某些内容,Karma 都会认为测试失败,因为订阅正如实际预期的那样,抛出未处理的错误。
我尝试过:
expect(service.methodUsingObservable).toThrowError();
expect(service.methodUsingObservable()).toThrowError();
expect(() => service.methodUsingObservable()).toThrowError();
但似乎没有人教系统接受测试成功,并且测试失败。
Chrome 62.0.3202 (Windows 10.0.0) MachinService should handle the error when one occurs FAILED
Error: Failing HTTP call
at UserContext.<anonymous> src/app/shared/services/machin.service.spec.ts:12:64)
...
在这些条件下如何将测试标记为通过?
最佳答案
嗯,一种方法是删除 catchError
并实际处理订阅中的错误,甚至不必抛出错误:
subscribe(
(success)=>{},
(error)=>checkLocally(error))
)
这样您就可以在 Spy
中 returnValue(throwError())
并且 fakeAsync
不会提示,因为错误将是已处理。
关于angular - 预计 observable 在 Angular/Karma/Jasmine 测试中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366315/