How do I test a function that returns an observable using timed intervals in rxjs 5?

后端 未结 4 1931
感情败类
感情败类 2020-12-03 18:33

For example, I have a function like this:

export function timeRange(start: number, end: number): Rx.Observable {
  return Rx.Observable.interva         


        
4条回答
  •  情话喂你
    2020-12-03 18:51

    I faced the same problem recently and discovered marble testing which lets you write awesome visual tests that make timed Observable testing extremely easy.

    Marble testing abstracts time away and the tests run instantly (by using TestScheduler under the hood), but you still can test complex timed processes. This is an example test to give you an idea of the syntax:

    it('should set up an interval', () => {
      const expected = '----------0---------1---------2---------3---------4---------5---------6-----';
      expectObservable(Observable.interval(100, rxTestScheduler)).toBe(expected, [0, 1, 2, 3, 4, 5, 6]);
    });
    

    This actually is the official unit test from for Observable.interval from the rxjs5 repo: https://github.com/ReactiveX/rxjs/blob/master/spec/observables/interval-spec.ts

    Check out the official documentation for more info.

    Getting it running was a bit of a challenge, but all you basically need are the two files marble-testing.ts and test-helper.ts from this marble testing example project.

提交回复
热议问题