首页 > 解决方案 > Angular6 - 测试 HttpClient“点击”和“管道”

问题描述

我最近将我的 Angular5 项目升级到 Angular6,我不得不改变的一件事是围绕 HttpClient 的使用,引入了水龙头和管道。

我的代码现在如下:

public getCountryData(id: string): Country[] {
    const url = `${this.config.apiUrl}/${id}`;

    return this.http.get<CountryData>(url, this.noCacheOptions).pipe(
      tap(res => {
        res = this.convertToCountryArray(res);
        return res;
      }),
      catchError(error => this.handleError(error))
    );
}

我正在编写测试来涵盖我的 API 调用,我需要测试一个成功的 get 和一个错误,所以我编写了以下测试(前言 - 我是编写这些单元测试的新手,所以毫无疑问它可以做得更好,任何建议表示赞赏!):

  it('should call getCountryData, inject([HttpTestingController, CountryDataService, ConfigService],
    (httpMock: HttpTestingController, dataService: CountryDataService, configService: ConfigService) => {

        expect(CountryDataService).toBeTruthy();

        const id = 'cfc78ed9-4e771215efdd64b1';

        dataService.getCountryData(id).subscribe((event: any) => {
          switch (event.type) {
            case HttpEventType.Response:
              expect(event.body).toEqual(mockCountryList);
          }
        }, (err) => {
          expect(err).toBeTruthy();
        });

        const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);

        expect(mockReq.cancelled).toBeFalsy();
        expect(mockReq.request.responseType).toEqual('json');

        try {
          mockReq.flush(new Error(), { status: 404, statusText: 'Bad Request' });
        } catch (error) {
          expect(error).toBeTruthy();
        }

        httpMock.verify();
    })
);

当我查看代码覆盖率时,我可以看到并非所有分支都被我的测试覆盖。但我不确定要改变什么才能正确覆盖它。任何关于我需要更改的指示或建议都会很棒!

在此处输入图像描述

提前致谢!

标签: unit-testingcode-coverageangular6istanbulangular-httpclient

解决方案


所以我很快发现了如何解决这个问题。只是发布以防其他人发现它有用。我将 api 的正面和负面测试分为两个单元测试,如下所示:

  it('should call getCountryData with success', () => {

    const id = 'cfc78ed9-4e771215efdd64b1';

    dataService.getCountryData(id).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Response:
          expect(event.body).toEqual(mockCountryData);
      }
    });

    const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);

    expect(mockReq.cancelled).toBeFalsy();
    expect(mockReq.request.responseType).toEqual('json');

    mockReq.flush(mockCountryData);
    httpMock.verify();
  });

  it('should call getCountryData with failure', () => {

    const id = 'cfc78ed9-4e771215efdd64b1';

    dataService.getCountryData(id).subscribe((event: HttpEvent<any>) => { },
    (err) => {
      expect(err).toBeTruthy();
    });

    const mockReq = httpMock.expectOne(`${configService.apiUrl}/${id}`);

    expect(mockReq.cancelled).toBeFalsy();
    expect(mockReq.request.responseType).toEqual('json');

    mockReq.flush({ errorType: 2,
      errorDetails: [{ errorKey: 'errorKey', errorCode: '1001', errorMessage: 'errorMessage' }],
      errorIdentifier: 'cfc78ed9-4e771215efdd64b1' },
      { status: 404, statusText: 'Bad Request' });
    httpMock.verify();
  });

主要区别在于一个刷新成功对象和一个刷新错误。


推荐阅读