Home > Software engineering >  Angular - Writing unit test case for switchMap
Angular - Writing unit test case for switchMap

Time:11-30

below are my two service methods

    getCountries(offset: number) {
          let url = this.configManagerService.countriesApiUrl;
          const httpHeaders = this.getHeaders();
          return this.httpClient.get(url   offset, { headers: httpHeaders });
        }
        
    getAllCountries(offset: number = 0, resultOld: any[] = []) {
      return this.getCountries(offset).pipe(
      
        //not getting covered
        switchMap((result: any) => {
          offset = result.length > 0 ? offset   result.length : -1;
          return offset >= 0
            ? this.getAllCountries(offset, [...resultOld, ...result])
            : of(resultOld);
        //not getting covered
        
        })
      );
    }

I was able to write unit test case which covered getCountries function, but not able to understand how can I cover the code which I mentioned between the comments regarding switchMap. Tried to google it but not able to find anything which suits my requirements. Any help here would be greatly appreciated. Thanks.

CodePudding user response:

Here is an example of one case.

it('returns resultOld if result length is zero', (done: DoneFn) => {
  const resultOld = [];
  spyOn(service, 'getCountries').and.returnValue(of(resultOld));
  service.getAllCountries(2, resultOld).subscribe(results => {
    expect(results.length).toBe(0);
    done();
  });
});

it('calls getAllCountries over and over until converge', (done: DoneFn) => {
  const resultOld = [{ name: 'USA' }];
  spyOn(service, 'getCountries').and.returnValue(of(resultOld));
  service.getAllCountries(-1, resultOld).subscribe(results => {
    expect(results.length).toBe(1);
    done();
  });
});
  • Related