【问题标题】:Unit testing for service class which calls backendserver- angular调用 backendserver-angular 的服务类的单元测试
【发布时间】:2020-10-06 15:31:57
【问题描述】:

我有一个服务类方法,它对后端服务器进行 GET 调用,后端服务器返回人员数组的响应,其中包含字段-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
                    };
                });
            }
        })
    );
}

【问题讨论】:

标签: angular karma-jasmine testcase angular-test


【解决方案1】:

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

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

【讨论】:

  • 您能指导如何解决测试覆盖中其他部分未采取警告的问题吗????这是我写的测试用例: --> it('should get search results', () => { peopleService.searchPeople('testname1').subscribe( res => expect(peopleMockResponse).toEqual(peopleMockResponse, '应该返回预期结果'), 失败); const req = httpTestingController.expectOne('/url'); expect(req.request.method).toEqual('GET'); req.flush(peopleMockResponse); });
  • 要涵盖这部分,您需要模拟 httpTestingController 以使 if(data) 中的 data 的值是虚假的,但在这种情况下,我不确定您的期望语句将包含什么。
【解决方案2】:
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();
});
    
        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2017-06-03
    相关资源
    最近更新 更多