Angular 7 (RxJs6) - 单元测试 - 如何检查服务是否 return throwError?
Angular 7 (RxJs6) - Unit tests - How to check if service return throwError?
我想测试 throwError 部分。 OK测试OK。我想测试如果使用 getById
错误的 id 0
, getById
return 错误 (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.
我改
throwError('Spada not found');
来自
return throwError('Spada not found');
我想测试 throwError 部分。 OK测试OK。我想测试如果使用 getById
错误的 id 0
, getById
return 错误 (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.
我改
throwError('Spada not found');
来自
return throwError('Spada not found');