Angular 如何测试可观察计时器

Angular 如何测试可观察计时器,angular,unit-testing,timer,jasmine,angular5,Angular,Unit Testing,Timer,Jasmine,Angular5,我正在尝试测试这段代码: `discardChanges() { const timer = Observable.timer(1000); this.showSpinner = true; timer.subscribe(() => { this.showSpinner = false; this.toastr.success('Changes discarded'); this.loadCondition(this

我正在尝试测试这段代码:

`discardChanges() {
    const timer = Observable.timer(1000);
    this.showSpinner = true;
    timer.subscribe(() => {
        this.showSpinner = false;
        this.toastr.success('Changes discarded');
        this.loadCondition(this.condition);
        this.studyConditionsForm.markAsPristine();
    });
}`
和茉莉花一起做,就像:

`xit('should discard changes and navigate to conditions', fakeAsync(() => {
    expect(component.showSpinner).toBeFalsy();
    enter code herecomponent.discardChanges();
    expect(component.showSpinner).toBeTruthy();
    tick(1000);
    fixture.detectChanges();
    expect(component.showSpinner).toBeFalsy();
    discardPeriodicTasks();
  })
);`
但是当运行
ng测试时
我得到了这个错误:

错误:队列中仍有1个计时器。​​

我读过很多帖子,但我没有让它工作,事实上,我在另一个测试中也遇到了同样的问题,但在多次尝试之前,它神奇地工作了(老实说,我不喜欢魔术)

我希望有人能指导我,事实上,如果有其他最好的方法,而不是使用
const timer=Observable.timer(1000)
,并使其可测试将是伟大的


谢谢。

我正在使用rxjs 6.x,复制代码并运行
ng test
命令,测试通过。 您可以尝试将rxjs更新到新版本并再次测试(注意:rxjs 6.x中没有
Observable.timer
) 以下是代码:

import { timer } from 'rxjs';
 discardChanges() { // method of component class
    const source = timer(1000);
    this.showSpinner = true;
    source.subscribe(() => {
        console.log(1)
        this.showSpinner = false;
    });
  }
测试规范代码:

 it('should test discardChanges', fakeAsync(() => {
        expect(component.showSpinner).toBeFalsy();
        component.discardChanges()
        expect(component.showSpinner).toBeTruthy();
        tick(1000);
        expect(component.showSpinner).toBeFalsy();
        discardPeriodicTasks()
      }));

尝试使用可观察计时器(1000)。使用(1)
我从未使用Jasmine进行测试,但使用可观察计时器时,请确保取消订阅计时器
this.subscription=timer.subscripte(…);订阅。取消订阅()take()在take arg times后取消订阅我已将代码更新为
丢弃更改(){const timer=Observable.timer(1000).take(1);this.showSpinner=true;timer.subscribe(()=>{this.showSpinner=false;this.toastr.success('Changes discarded');this.loadCondition(this.condition));this.studyConditionsForm.markAsPristine();});}
根据注释和相同的错误,我还尝试了subscription.unsubscripte();但是它冻结了。