首页 > 解决方案 > rxjs如何期望一个可观察的抛出错误

问题描述

在我的 TypeScript 应用程序中,我有一个返回 rxjs Observable 的方法,在某些情况下,它可以返回throwError

import { throwError } from 'rxjs';

// ...

getSomeData(inputValue): Observable<string> {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // ...
}

我如何编写测试来涵盖这种特定情况?

标签: angulartypescriptrxjsjasmineangular-test

解决方案


您可以使用 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' });
    });
  });
});

有关如何编写这些测试的更多信息,请查看此链接


推荐阅读