Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular testing async function generate error - 1 periodic timer(s) still in the queue

I'm trying to test that two async functions. The problem is that one of the functions is called every 10 seconds automatically. I tried to use tick() or flush() but I still get the same error: 1 periodic timer(s) still in the queue. How can I resolve it? My code:

 ngOnInit(): void {
    const dialogRef = this.openProgressDialog();
    this.getSubscription = this.getAll();
    dialogRef.close();

    this.postSubscription = interval(10000).subscribe(() => {
      this.sendAll();
      this.dataSource.data = this.jobs;
      this.table.renderRows();
    });
  }

The test:

test("test", fakeAsync(() => {
    const getSpy = spyOn(otdRepositoryMock, "getAll").and.returnValue(of(jobs));
    const getSubscribeSpy = spyOn(otdRepositoryMock.getAll(), "subscribe");
    const postSpy = spyOn(otdRepositoryMock, "sendAll").and.returnValue(of(jobs));
    const postSubscribeSpy = spyOn(otdRepositoryMock.sendAll([2]), "subscribe");
    component.ngOnInit();
    //tick();
    //flush();
    expect(getSpy).toHaveBeenCalled();
    expect(getSubscribeSpy).toHaveBeenCalled();
    expect(postSpy).toHaveBeenCalled();
    expect(postSubscribeSpy).toHaveBeenCalled();
  }));
like image 279
anyway07 Avatar asked Sep 05 '26 18:09

anyway07


1 Answers

In short, you DON'T need flush, you DO need tick() and you should add the following to the bottom of your test, following your expectations:

      discardPeriodicTasks(); 

This will clear out any remaining timers you have before executing the next test.

So in your example (edited for brevity):

test("test", fakeAsync(() => {

   const getSpy = ...

   component.ngOnInit();
   tick(10000);

   expect(getSpy).toHaveBeenCalled() . . .

   discardPeriodicTasks(); 
 }));

Hope this helps,

like image 89
djmarquette Avatar answered Sep 07 '26 14:09

djmarquette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!