【发布时间】: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