Unit testing for service class which calls backendserver- angular

53 views Asked by At

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

There are 2 answers

0
Javacoder On BEST ANSWER
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();
});
    
        
2
Kunal Karmakar On

You could simply import HttpClientTestingModule in your TestBed and using the HttpTestingController you can simply expect(URL) and inject a fake response through flush().

You may refer to the example from this page.