Gavi
Gavi

Reputation: 1478

Angular - How to test method that calls a callback

I'm using Angular 11 with typescript and I don't know how to test the paths in which the method raise an exception.

  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;
      }
    });
  }

As testing framework I'm using jasmine and karma.

How can I test the path when an exception is thrown?

Upvotes: 1

Views: 76

Answers (2)

Andrei
Andrei

Reputation: 12036

observables were implemented with ability to handle asynchronisity in mind. so you will be required to make your test asynchronious with the help of fakeAsync. in fakeAsync tests tick function allows you to "flush" everything hapenning asynchroniously. in your case it is possible to take advantage of that, and expect tick to throw. like this:

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

Upvotes: 1

Andrei
Andrei

Reputation: 12036

I assume you are mocking your service with spy methods at some point of test setup. to make your test go though error way just return error observable from your method. use throwError observable creation fn

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

Upvotes: 1

Related Questions