I encountered a similar issue, but due to commenting constraints on other questions, I had to create a new one. The problem lies in a jasmine test where a function is expected to manage an error from a service call. The service call returns an RxJS `Observable` of an `HttpResponse`, yet the function under test does not seem to receive any response from the service, even when using a spy to simulate the error. Here's the code structure:
component.ts:
public thingThatCallsService() {
this.foo = false;
this.service.bar()
.subscribe(
(res) => {log(res)},
(err) => {
log(err) // Logs empty string during test
if (err.status === 400) this.foo = true;
}
);
}
mockService.ts: (Used by the test suite instead of the actual service)
public bar() {
return of(new HttpResponse());
}
test.ts:
it("sets foo to true if bar returns an error", fakeAsync(() => {
spyOn(service, "bar").and.returnValue(
throwError(() => new HttpErrorResponse({status: 400}))
);
component.thingThatCallsService();
tick();
componentFixture.detectChanges();
expect(service.bar).toHaveBeenCalled();
expect(component.foo).toBeTrue(); // Failing consistently
}))
Similar questions like this and this lack suitable solutions – some suggest returning a string rather than an object with a `status` field, or provide outdated/inaccurate code snippets.
It's worth mentioning that the code functions correctly outside the test environment; when the service encounters an error with a specific status code, `foo` is indeed set to true.
If you have any insights on how to properly handle errors thrown by the `Observable` for subscription handling, your guidance would be greatly appreciated. Thank you!