Imagine I have a component that contains the following method:
someMethod() {
this.someService
.doServicesMethod(this.id)
.pipe(
finalize(() => (this.loading = false)),
catchError((e) => {
this.showErrorMessage = true;
return throwError(e);
}),
)
.subscribe({
next: (result) => {/* handle result*/},
});
}
Now, I want to create a unit test using jest. Here is how I proceed:
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();
}
}),
);
Unfortunately, the unit test does not work as expected. I initially attempted running the test without waitForAsync
, which caused the error to be detected in subsequent tests, leading to failure with someError
.
Using waitForAsync
helps detect the error but not within the try-catch-block, causing the test itself to fail.
Even calling tick();
after component.someMethod();
detects the error, however, it is not properly caught and results in a failure with someError
.
I am having trouble finding a solution, so if anyone has any ideas on how to make this test successful, please share them!