How do I mock RxJs 6 timer?

折月煮酒 提交于 2019-11-30 13:40:15

As you are using fakeAsync, you can rely upon its patching of setInterval to fake the implementation of the timer observable.

However, you will need to clobber the asyncScheduler instance's now method, as it returns Date.now(). (Strictly speaking, this isn't necessary for the timer observable, as you've used it, but it will matter for some other observables - e.g. the observable returned by the delay operator).

You can get things to work pretty easily if you use beforeEach and afterEach to clobber the now method and to configure a function that keeps track of the fake time:

import { fakeAsync, tick as _tick } from '@angular/core/testing';
import { asyncScheduler, of, timer } from 'rxjs';
import { delay } from 'rxjs/operators';

describe('fakeAsync and RxJS', () => {

  let tick: (milliseconds: number) => void;

  beforeEach(() => {
    let fakeNow = 0;
    tick = milliseconds => {
      fakeNow += milliseconds;
      _tick(milliseconds);
    };
    asyncScheduler.now = () => fakeNow;
  });

  it('should support timer with fakeAsync', fakeAsync(() => {
    const source = timer(100);
    let received: number | undefined;
    source.subscribe(value => received = value);
    tick(50);
    expect(received).not.toBeDefined();
    tick(50);
    expect(received).toBe(0);
  }));

  it('should support delay with fakeAsync', fakeAsync(() => {
    const source = of(0).pipe(delay(100));
    let received: number | undefined;
    source.subscribe(value => received = value);
    tick(50);
    expect(received).not.toBeDefined();
    tick(50);
    expect(received).toBe(0);
  }));

  afterEach(() => {
    delete asyncScheduler.now;
  });
});

Actually, because relying upon fakeAsync to mock the time-based observable is likely to be useful, I've added a fakeSchedulers function to my rxjs-marbles package. See fake-spec.ts for example usage.

The implementation is basically the same as that in the above snippet - just wrapped up in a function.


Since writing this answer and adding fakeSchedulers to rxjs-marbles, I've written an article about Testing with Fake Time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!