【问题标题】:How to test Observable.timer如何测试 Observable.timer
【发布时间】:2018-01-17 16:40:13
【问题描述】:

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

`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();
    });
}`

像 Jasmine 那样做:

`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 test 时出现此错误:

Error: 1 timer(s) still in the queue.​​

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

我希望有人可以指导我,实际上如果有另一种最好的方法而不是使用const timer = Observable.timer(1000) 并使其可测试会很棒!

谢谢。

【问题讨论】:

  • 尝试使用Observable.timer(1000).take(1)
  • 我从未使用 Jasmine 进行测试,但在使用 Observable 计时器时,请确保取消订阅计时器。 this.subscription = timer.subscribe(...);subscription.unsubscribe();
  • take() 在 take arg 次后取消订阅
  • 我已根据 cmets 将我的代码更新为 discardChanges() { 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.unsubscribe();但它冻结了。

标签: angular unit-testing timer jasmine angular5


【解决方案1】:

我使用的是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()
      }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多