Search code examples
angularkarma-jasminerxjs6

Angular 7 (RxJs6) - Unit tests - How to check if service return throwError?


I want test throwError part. OK test is OK. I want test if use getById with a wrong id 0, getById return an error (throwError)

My service:

getById(fooId): Observable<Foo> {
  return this.getAll().pipe(mergeMap(foos => {
    const foo: Foo= foos.find(({id}) => id === fooId);
    if (foo) {
      return of(foo);
    } else {
      throwError('foo not found');
    }
  }
));

}

My unit tests:

it('...', () => {

    service.getById(0).subscribe(() => {
      fail('expected error');
    }, (error) => {
      expect(error).toBe('foo not found');
    });

    const res= httpMock.expectOne({ url: '/api/admin/foo', method: 'GET' });
    res.flush(
      [
        {
          'id': 1,
          'name': 'foo1'
        },
        {
          'id': 2,
          'name': 'foo2'
        }
      ]);
  });

I have this error:

TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Solution

  • I change

    throwError('Spada not found');
    

    by

    return throwError('Spada not found');