Angular 7(RxJs6) - 单元测试 - 如何检查服务是否返回throwError?

问题描述 投票:0回答:1

我想测试throwError部分。好的测试没问题。我想测试如果使用getById与错误的id 0getById返回错误(throwError

我的服务:

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

}

我的单元测试:

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

我有这个错误:

TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
angular karma-jasmine rxjs6
1个回答
0
投票

我改变

throwError('Spada not found');

通过

return throwError('Spada not found');
© www.soinside.com 2019 - 2024. All rights reserved.