在我的 TypeScript 应用程序中,我有一个返回 rxjs Observable 的方法,在某些情况下,它可以返回 throwError :
import { throwError } from 'rxjs';
// ...
getSomeData(inputValue): Observable<string> {
if (!inputValue) {
return throwError('Missing inputValue!');
}
// ...
}
我如何编写测试来涵盖这个特定案例?
最佳答案
您可以使用 RxJS Marble 图表测试来测试它。就是这样:
const getSomeData = (inputValue: string): Observable<string> => {
if (!inputValue) {
return throwError('Missing inputValue!');
}
// e.g.
return of(inputValue);
};
describe('Error test', () => {
let scheduler: TestScheduler;
beforeEach(() => {
scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
it('should throw an error if an invalid value has been sent', () => {
scheduler.run(({ expectObservable }) => {
const expectedMarbles = '#'; // # indicates an error terminal event
const result$ = getSomeData(''); // an empty string is falsy
expectObservable(result$).toBe(expectedMarbles, null, 'Missing inputValue!');
});
});
it('should emit an inputValue and immediately complete', () => {
scheduler.run(({ expectObservable }) => {
const expectedMarbles = '(a|)';
const result$ = getSomeData('Some valid string');
expectObservable(result$).toBe(expectedMarbles, { a: 'Some valid string' });
});
});
});
有关如何编写这些测试的更多信息,请查看 this link .
关于angular - rxjs 如何期望 observable 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57804709/