简体   繁体   English

如何测试Observable.timer

[英]How to test Observable.timer

I'm trying to test this piece of code: 我正在尝试测试这段代码:

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

doing it with Jasmine like: 像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();
  })
);`

but when running ng test I got this error: 但是在运行ng test我遇到了这个错误:

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

I have read many post and I don't make it work, actually I had the same issue with another test doing it this way but magically worked before many tries (I don't like magic to be honest). 我已阅读了很多帖子而且我没有让它发挥作用,实际上我有同样的问题与另一个测试这样做但在多次尝试之前神奇地工作(我不喜欢魔术说实话)。

I hope someone can guide me, actually if there is another best way rather than using const timer = Observable.timer(1000) and make it testable would be great! 我希望有人可以指导我,实际上如果有另一种最好的方法,而不是使用const timer = Observable.timer(1000)并使其可测试将是伟大的!

Thanks. 谢谢。

I'm using rxjs 6.x,copy your code and run ng test command, and test passes. 我正在使用rxjs 6.x,复制代码并运行ng test命令和测试通过。 You can try to update rxjs to newer version and test again(attention: no Observable.timer in rxjs 6.x) Here are codes: 您可以尝试将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;
    });
  }

test specification code: 测试规范代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM