使用setTimeout

时间:2018-09-05 18:47:12

标签: angular unit-testing karma-jasmine

我的组件看起来像这样,在Init中,我从服务中获取初始数据,然后每15秒调用一次相同的函数来更新该数据:

networkGraph: NetworkGraphComponent;
hideSpinner: boolean = false;
ngAfterViewInit() {
      this.getTopology();
}

getTopology() {
      clearTimeout(this.timeoutHandler);
      this.topologyService.getTopology().subscribe((topology: any) => {

            ...do stuff...

            if (topology) {

                setTimeout(()=>{ // hack to fix ngIf 
                    this.hideSpinner = true;
                });
                this.networkGraph.topology = topology;
                this.timeoutHandle = setTimeout(function(){
                    this.getTopology();
                }, 15000);
            }

    });

我将如何编写单元测试来对此进行测试?总是失败说我队列中有计时器。我已经阅读过https://medium.com/@golbie/angular-testing-async-stuff-in-the-fakedasync-zone-vs-providing-custom-schedulers-27a7f83c7774,并尝试了其中的内容,但是我猜我做得不好,因为我仍然得到相同的结果。

 it('should create the component', fakeAsync(()=>{
    tick(20000)
    fixture.detectChanges();
    fixture.whenStable().then(()=>{
        expect(component).toBeTruthy();
    })

}));

1 个答案:

答案 0 :(得分:0)

您尝试使用done()吗?

it('should create the component', (done) => {

    fixture.detectChanges();
    fixture.whenStable().then(()=>{
        done(); //waits for promise to complete
        expect(component).toBeTruthy();
    })

});