【发布时间】:2021-08-04 14:15:57
【问题描述】:
假设我得到了一个使用以下方法的组件:
someMethod() {
this.someService
.doServicesMethod(this.id)
.pipe(
finalize(() => (this.loading = false)),
catchError((e) => {
this.showErrorMessage = true;
return throwError(e);
}),
)
.subscribe({
next: (result) => {/* handle result*/},
});
}
现在我想用 jest 写一个单元测试,所以我喜欢:
it(
'should test someMethod',
waitForAsync(() => {
spyOn(someService, 'doServicesMethod').and.returnValue(throwError('someError'));
expect(component.showErrorMessage).toBeFalsy();
expect(component.loading).toBeTruthy();
try {
component.someMethod();
} catch (error) {
expect(component.loading).toBeFalsy();
expect(component.showErrorMessage).toBeTruthy();
}
}),
);
但是单元测试不起作用。起初我尝试不使用waitForAsync,在这种情况下,在此测试中未检测到错误,但在测试后以某种方式浮动并在下一次测试中被检测到,然后以someError 失败。
使用 waitForAsync 会检测到错误,但不会在 try-catch-block 中检测到错误,在这种情况下测试本身会失败。
在component.someMethod(); 检测到错误后调用tick();,因此测试跳转到catch 块,但错误实际上并没有被捕获 -> 无论如何测试都失败了someError。
我有点想不通,所以有人知道我是如何让这个测试工作的吗?
【问题讨论】:
标签: angular typescript unit-testing rxjs jestjs