我正在尝试测试这段代码:
`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/