调用后端服务器的服务 class 的单元测试- angular

Unit testing for service class which calls backendserver- angular

我有一个服务中的方法 class,它有一个对后端服务器和后端服务器的 GET 调用 returns 人员数组的响应,其中包含字段 - employedID、name 和 busnTitle。

你能帮忙覆盖下面几行吗?

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

您可以简单地在您的 TestBed 中导入 HttpClientTestingModule 并使用 HttpTestingController 您可以简单地 expect(URL) 并通过 flush() 注入虚假响应。

您可以参考 this 页面中的示例。

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