Angular-如何测试调用回调的方法



我将Angular 11与typescript一起使用,我不知道如何测试该方法引发异常的路径。

myMethod() {
this.myService.callBackend(id).subscribe(() => {
// do something when success
}, responseKo => {
if (responseKo instanceof HttpErrorResponse) {
if (responseKo.status === 400) {
// do something when we have bad request
} else {
throw responseKo;
}
} else {
throw responseKo;
}
});
}

作为测试框架,我使用茉莉花和因果报应。

当抛出异常时,如何测试路径?

可观察性的实现考虑到了处理异步性的能力。因此,您将被要求在fakeAsync的帮助下使您的测试异步。在CCD_ 2测试中,CCD_;"冲洗";一切都是异步发生的。在您的情况下,可以利用这一点,并期望tick投球。像这样:

it('should throw', fakeAsync(() => {
of(true).subscribe(() => {
throw new Error('something thrown');
});
expect(tick).toThrow();
}));

我假设您在测试设置的某个时刻使用间谍方法嘲笑您的服务。要使您的测试通过错误的方式,只需返回可从您的方法中观察到的错误。使用throwError可观测创建fn

it('it should react to errors', () => {
serviceMock.callBackend.and.returnValue(throwError(myErrorObject));
myComponent.myMethod();
});

最新更新