我无法在函数startTimer中创建测试计时器Observable的测试。我使用的是RXJS的6.3.1版本。
这是我的代码:
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();
}
}
我使用以下方法解决问题:
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();
});
});