Unit test case in angular for polling api call until the data is received

43 Views Asked by At

I have used the below code to call the api until the data is received. The below code will be keep on calling for every 5 seconds once until I get res["status"]=="Recieved" from the response.

import { switchMap, takeUntil } from 'rxjs/operators';

const INTERVAL = 5000;  // <-- poll every 5 seconds

export class someComponent implements OnInit, OnDestroy {
  closeTimer$ = new Subject<any>();

  ngOnInit() {
    timer(0, INTERVAL).pipe(      // <-- start immediately and poll every `INTERVAL` seconds
      switchMap(() => this.sendToBank()),  // <-- map to another observable
      takeUntil(this.closeTimer$)   // <-- close the subscription when `closeTimer$` emits
    ).subscribe({
      next: (res: any) => {
        if (res["status"]=="Recieved") {
          this.closeTimer$.next();  // <-- stop polling
        }
        // do something else
      },
      error: (error: any) => {
        // handle errors
        // note that any errors would stop the polling here
      }
    );
  }
}

Could you Please help me with the unit test cases for the above code? Thanks in advance.

0

There are 0 best solutions below