0

This question is sort of a duplicate, but since I can't comment on other questions I've had to open a new one.

I'm running into a bug in a jasmine test where a function is supposed to handle an error from a service call. The service call in question returns an RxJS Observable of an HttpResponse. The function being tested seems to not receive anything from the service, even when using a spy to throw the error. The code follows this 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: (The test suite is set to use this 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(); // Keeps failing
}))

Questions like this one and this one either have answers where a string should be returned, not an object with a status field; or answers that contain outdated/invalid code (for instance, new Error({status: 404}) is not a valid instantiation of an Error).

It should also be noted that the code works correctly outside of the test; i.e. when the service call encounters an error with a specific status code, foo is set to true.

Any advice on how to have the Observable properly throw an error for the subscription to handle would be much appreciated. Thanks!

1 Answers1

0

Can you try the following to see if it works?

spyOn(service, "bar").and.returnValue(
        throwError(() => ({ status: 400 }))
    );

Also see what the log outputs in this scenario as well. I am not sure why HttpErrorResponse does not work, it should work.

AliF50
  • 16,947
  • 1
  • 21
  • 37