代码之家  ›  专栏  ›  技术社区  ›  iamcootis

带setTimeout的角度单元测试

  •  1
  • iamcootis  · 技术社区  · 6 年前

    我的组件如下所示,在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 回复  |  直到 6 年前
        1
  •  1
  •   Omkar Porje    6 年前

    是否尝试使用done()?

    it('should create the component', (done) => {
    
        fixture.detectChanges();
        fixture.whenStable().then(()=>{
            done(); //waits for promise to complete
            expect(component).toBeTruthy();
        })
    
    });