Search code examples
angularunit-testingjestjsjasmine

Unit test cases for nested api calls in Angular


I'm trying to write unit test cases for nested API calls and don't know how to write unit test cases for the following scenario.

this.openService
      .createDocument(PIReq, this.id)
      .subscribe({
        next: (res1) => {
          const applicationReq = AppUtil.getApplicationRequest(
            this.openService.personDetails,
            res1.id
          );
          this.openService
            .createPersonAppliation(applicationReq, this.id)
            .subscribe({
              next: (res2) => {
                const personAppReqInfo: PersonApplicationIds = {
                  documentId: res1.id,
                  personApplicationId: res2.id,
                };
                
                if (this.openDataStoreService.details.length > 0) {
                  this.submitApplicationRequest();
                  this.invokeRequest();
                } else {
                  this.invokeRequest();
                }
              },
              error: () => {
                this.showSpinner = false;
              },
            });
        },
        error: () => {
          this.showSpinner = false;
        },
     });

Here is what I've tried

let sampleApplicationResponse!: ApplicationResponse;
jest.spyOn(openService, 'createPersonAppliation').mockReturnValueOnce(of(sampleApplicationResponse));
    openService.createPersonAppliation(applicationReq, component.id)
      .subscribe({
        next: applicationRes => {
          expect(applicationRes).toBe(sampleApplicationResponse);
        }
      });

This test case works, but the problem is that this test case doesn't contribute to anything in the coverage, any way to test all the lines in the nested api call? Jest/Jasmine anything is fine


Solution

  • After some research and help from my friends, I figured out a way. You can async if you want

    it("nested api calls, async () => {
      const spy1 = jest.spyOn(openService, "createDocument").mockReturnValueOnce(of(sampleResponse));
    
      const spy2 = jest.spyOn(openService, "createPersonAppliation").mockReturnValueOnce(of(sampleResponse));
    
      component.submit();
    
      expect(spy1).toBeCalled();
      expect(spy2).toBeCalled();
    });