Unit test Observed with delay operator

I am having a hard time getting my unit test to work alongside the Observable with delay statement. The app is built on Angular 2 and tests are run in karma / jasmine. I have tried the async and fakeAsync methods, but none of them work.

Here's a simplified code (no Angular 2) explaining my problem.

let mouseDownStream = Rx.Observable.fromEvent(document.body, 'mousedown');
let haveBeenCalled = false;
mouseDownStream.delay(200).subscribe(() => haveBeenCalled = true);

describe('mouse down event', () => {
  it('it should emit an event stream after 200ms', (done) => {
    document.body.dispatchEvent(new MouseEvent('mousedown'))
    expect(haveBeenCalled).toBeFalsy();

    // Don't want this setTimeout should use Angular tick(200) method instead but it not working.
    setTimeout(() => {
      expect(haveBeenCalled).toBeTruthy();
      done();
    }, 200)
  });
});

      

JSBin

+3


source to share


1 answer


The trick is to use a different scheduler. There is a special planner for testing, called ... TestScheduler

. This, combined with the marbled charts, allows for testing asynchronous threads.

Here is an example of the official specification of the delay operator :



it('should delay by absolute time period', () => {
  const e1 =   hot('--a--b--|  ');
  const t =   time(  '---|     ');
  const expected = '-----a--b--|';
  const subs =     '^          !';

  const absoluteDelay = new Date(rxTestScheduler.now() + t);
  const result = e1.delay(absoluteDelay, rxTestScheduler);

  expectObservable(result).toBe(expected);
  expectSubscriptions(e1.subscriptions).toBe(subs);
});

      

More details are hiding in this thread: https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md

0


source







All Articles