如何在茉莉花大理石中创建可观察的计时器测试?

时间:2018-09-12 19:23:51

标签: javascript angular typescript jasmine

我无法创建测试以测试可在功能startTimer中观察到的计时器。我使用的是6.3.1版的RXJS。

这是我的代码:

private createSubscribe(): void {
  if (this.timer) {
    this.subscription = this.timer.subscribe(() => {
      this.cream().then(() => {
        this.subscription.unsubscribe();
        this.subscription = null;
        this.timer = null;
        this.startTimer(this.config.period);
      });
    });
  }
}

private startTimer(period): void {
  if (period) {
    this.timer = timer(period * 1000);
    this.createSubscribe();
  }
}

1 个答案:

答案 0 :(得分:0)

我使用以下方法解决了我的问题:

it('startTimer: should call createSubscribe and set timer with observable emited in 5000ms.', () => {

  const scheduler = new TestScheduler((actual, expected) => {
    expect(actual).toEqual(expected);
  });

  scheduler.run(helpers => {
    const { expectObservable } = helpers;
    const period = 5;
    const expected = '5000ms (a|)';
    spyOn(helper, <any>'createSubscribe');

    helper['startTimer'](period);

    expectObservable(helper['timer']).toBe(expected, {a : 0});
    expect(helper['createSubscribe']).toHaveBeenCalled();
  });
});