[英]How to test Observable.timer
我正在嘗試測試這段代碼:
`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)
並使其可測試將是偉大的!
謝謝。
我正在使用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()
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.