Home > Enterprise >  Angular test throwError
Angular test throwError

Time:03-30

I am having some difficulties making a test in angular.

I have a function in a service that goes like this:

 public getConfigFromData(conf: string, data: any): Observable<any> {
    if (!conf) {
      return throwError(`Error`);
    } else if (data) {
      return this.getConfig(conf, data);
    } else {
      return throwError('Other error');
    }
  }

And I'm having some problems when testing the error thrown. This is the following test:

it('...', () => {
    expect(() => {
      service.getConfigFromData(null, '');
    }).toThrowError('Error');
  });

The error that I get from jasmine is

Error: Expected function to throw an Error.

I've been trying to find in other answers but couldn't obtain any conclusion. Can anyone guess what I am missing or doing wrong? Thank you very much in advance.

CodePudding user response:

I think throwError returns an observable and you need to subscribe to the method for the observable to take flight.

Try this:

it('...', (done: DoneFn) => {
      service.getConfigFromContext(null, '').pipe(take(1)).subscribe({
      next: () => {},
      // subscribe, make assertion in the error block and call done to
      // let jasmine know you're done with the unit test
      error: (error) => { expect(error).toBeTruthy(); done(); }
   });

  });

I think .toThrowError is for regular JavaScript of throw new Error('error');.

CodePudding user response:

The returned throwError is an Observable of type Observable<never> that will error with the specified error immediately upon subscription. Hence, to make your test work, you would have to subscribe to the Observable or may simply transform it to a Promise to see the error be thrown. This can be done using async/await as follows:

it('#getConfigFromData should throw Error', async () => {
  try {
     await getConfigFromData(null, '').toPromise().then(() => null);
     fail('should have thrown Error')
  } catch (error) {
     expect(error).toBe('Error')
  }
});
  • Related