2

My component looks like this, where in the Init I get my initial data from a service and then I call the same function every 15 seconds to update that data:

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);
            }

    });

How would I write a unit test to test this? It keeps failing out saying I have timers in the queue. I have read this https://medium.com/@golbie/angular-testing-async-stuff-in-the-fakedasync-zone-vs-providing-custom-schedulers-27a7f83c7774 and attempted what is in there, but I'm guessing I didn't do it correctly because I still got the same results.

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

}));
iamcootis
  • 2,203
  • 3
  • 18
  • 22

1 Answers1

1

Did you try using done() ?

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

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

});
Omkar Porje
  • 278
  • 1
  • 5