angular - 如何测试 Observable.timer

标签 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.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 时出现了这个错误:

错误: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()
      }));

关于angular - 如何测试 Observable.timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305993/

相关文章:

Angular 2共享服务变量返回未定义

c# - 测试类转换方法的正确方法

c# - 10 秒后重定向到新的 wpf 窗口?

c# - AudioPlayerAgent、计时器和网络服务

angular - Angular 是否有标签输入组件?

Angular 17 窗口未定义

angular - 树 Material angular 2选中状态

c# - 关于模拟 EF 5 和测试存储库模式的一些问题

javascript - 编写 JavaScript 测试来测试其他函数的调用,而不实际调用它们

windows - KillTimer 是必需的吗?