angular - rxjs如何期望一个可观察的抛出错误
问题描述
在我的 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' });
});
});
});
有关如何编写这些测试的更多信息,请查看此链接。
推荐阅读
- javascript - 如果特定用户是@,则说一个短语
- html - 如何定位引导导航栏 (v4.5) 的 HTML 元素以使用 CSS 自定义样式
- python-3.x - 设置一个变量等于熊猫数据框中相邻列中的值
- javascript - 如何使用 Javascript 创建 JSON 对象?
- video - 上传到 AppStore Connect 的 App Preview 图像的云图标
- javascript - 如何在 v-calendar 中更改周末的颜色(周六和周日分别为不同的颜色)
- swagger - 大摇大摆地限制查询参数
- android - 如何实例化扩展 AndroidViewModel 的 ViewModel?
- python - 在我引用之前未分配全局变量的问题
- vega-lite - Vega-Lite X 轴标签未完整显示