Search code examples
angularkarma-jasminetestcaseangular-test

Unit testing for service class which calls backendserver- angular


I have a method in-service class which has a GET Call to the backend server and backendserver returns a response of people array with fields - employedID ,name, and busnTitle.

Could you help to cover the below lines?

searchPeople(searchWord: string): Observable<People[]> {
    return this.http.get<any>("{URL}").pipe(
        map(data => {
            if (data) {
                return data.persons.map(p => {
                    return {
                        eId: p.emplNtId,
                        name: p.name,
                        jobTitle: p.busnTitle
                    };
                });
            }
        })
    );
}

Solution

  • Solution:
            1) people-list-mock.json
            {
                "persons": [{
                        "emplNtId:": "123456",
                        "name": "testname",
                        "busnTitle": "Tester"
                    },
                    {
                        "emplNtId:": "1234",
                        "name": "testname",
                        "busnTitle": "Developer"
                    }
                ]
            }
            
            Added this in ts file 
            const peopleMockResponse: any = require('people-list-mock.json');
            
             it('should return an Observable<People[]> - success', () => {
      peopleService.searchPeople(mockName).subscribe(
        (people) => {
          expect(people.length).toBe(2);
        });
      const req = httpTestingController.expectOne('{URL}');
      expect(req.request.method).toBe('GET');
      req.flush(peopleMockResponse);
      httpTestingController.verify();
    });
    
    it('should not return response - failed ', () => {
      peopleService.searchPeople(mockName).subscribe(
        (people) => {
          expect(people).toBeUndefined();
        });
      const req = httpTestingController.expectOne('{URL}');
      expect(req.request.method).toBe('GET');
      req.flush(null);
      httpTestingController.verify();
    });