简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM