Search code examples
angularrxjsintervalstestcase

How to write test case for rxjs interval in angular 8?


I have one method "intervalCall()" into app.component.ts and sending the request every 60 seconds using rxjs interval, so want to test case for it for spect file, below is the method.

intervalCall() {
    interval(60 * 1000)
      .pipe(mergeMap(() => this.XYZService.XYZmethod()))
      .subscribe((data: StatusDependents) => {
        if (data.status === 'UP') {
          location.reload();
        }
      });
  }

this.XYZService.XYZmethod() is my service call which I am sending every 60 seconds.

I have write down below test case, still getting error with 1 periodic timer(s) still in the queue.

 describe('#intervalCall', () => {
    it('should call intervalCall method when status is UP', fakeAsync(() => {
      const statusData: StatusDependents = { status: 'UP' };
      const statusSpy = jest.spyOn(userService, 'statusDependents').mockReturnValue(of(statusData));
      component.intervalCall();
      fixture.detectChanges();
      tick(180500);
      expect(statusSpy).toHaveBeenCalled();
      flush();
    }));
  });

Solution

  • Use fakeAsync. See how it's used here: https://v8.angular.io/guide/testing

    The main advantage I've found is that you aren't waiting real seconds while unit testing, you can use tick(180500) to jump ahead 3 minutes and ½ seconds instantly.