angular - rxjs 如何期望 observable 抛出错误

标签 angular typescript rxjs jasmine angular-test

在我的 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/

相关文章:

Angular2 Material 映射问题

angular - 如何同步两个 Angular Material 分页器?

javascript - TypeORM 和 Node JS 中的连接表

javascript - 为什么我不能将 .map() 函数链接到可观察对象上

javascript - 是否可以从 rxjs-timeout-error 中获取请求信息?

wordpress - Ionic 2 和 wordpress(如何“一分钟前、几小时前等”)

angular - 在angular2中自动调整文本区域

angular - 模态返回数据类型检查

javascript - 源有 2 个元素,但目标只允许 1 个。Typescript 扩展运算符

node.js - 如何使用 RxJS、MySQL 和 NodeJS