Nodejs Typescript笑话单元测试覆盖率显示了一些要覆盖的代码

这是我的nodejs打字稿类,是针对isHealthy()公共方法的笑话单元测试。

测试覆盖率表明this.pingCheck()随后的block,catch和last return语句未被覆盖。 请告知。

我们可以对pingCheck私有方法进行单元测试吗?

这是我的课程

import { HttpService,Injectable } from '@nestjs/common';
import { DependencyUtlilizationService } from '../dependency-utlilization/dependency-utlilization.service';
import { ComponentType } from '../enums/component-type.enum';
import { HealthStatus } from '../enums/health-status.enum';
import { ComponentHealthCheckResult } from '../interfaces/component-health-check-result.interface';
import { ApiHealthCheckOptions } from './interfaces/api-health-check-options.interface';
@Injectable()
export class ApiHealthIndicator {
  private healthIndicatorResponse: {
    [key: string]: ComponentHealthCheckResult;
  };
  constructor(
    private readonly httpService: HttpService,private readonly dependencyUtilizationService: DependencyUtlilizationService,) {
    this.healthIndicatorResponse = {};
  }

  private async pingCheck(api: ApiHealthCheckOptions): Promise<boolean> {
    let result = this.dependencyUtilizationService.isRecentlyUsed(api.key);
    if (result) {
      await this.httpService.request({ url: api.url }).subscribe(() => {
        return true;
      });
    }
    return false;
  }

  async isHealthy(
    listOfAPIs: ApiHealthCheckOptions[],): Promise<{ [key: string]: ComponentHealthCheckResult }> {
    for (const api of listOfAPIs) {
      const apiHealthStatus = {
        status: HealthStatus.fail,type: ComponentType.url,componentId: api.key,description: `Health Status of ${api.url} is: fail`,time: Date.now(),output: '',links: {},};
      await this.pingCheck(api)
        .then(response => {
          apiHealthStatus.status = HealthStatus.pass;
          apiHealthStatus.description = `Health Status of ${api.url} is: pass`;
          this.healthIndicatorResponse[api.key] = apiHealthStatus;
        })
        .catch(rejected => {
          this.healthIndicatorResponse[api.key] = apiHealthStatus;
        });
    }
    return this.healthIndicatorResponse;
  }
}

这是我的单元测试代码。 运行npm run test时出现以下错误

(节点:7876)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“状态”

(节点:7876)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。引发此错误的原因可能是抛出了一个没有catch块的异步函数,或者是拒绝了一个.catch()无法处理的承诺。 (拒绝ID:6)


import { HttpService } from '@nestjs/common';
import { Test,TestingModule } from '@nestjs/testing';
import { DependencyUtlilizationService } from '../dependency-utlilization/dependency-utlilization.service';
import { ApiHealthIndicator } from './api-health-indicator';
import { ApiHealthCheckOptions } from './interfaces/api-health-check-options.interface';
import { HealthStatus } from '../enums/health-status.enum';

describe('ApiHealthIndicator',() => {
  let apiHealthIndicator: ApiHealthIndicator;
  let httpService: HttpService;
  let dependencyUtlilizationService: DependencyUtlilizationService;
  let dnsList: [{ key: 'domain_api'; url: 'http://localhost:3001' }];

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ApiHealthIndicator,{
          provide: HttpService,useValue: new HttpService(),},{
          provide: DependencyUtlilizationService,useValue: new DependencyUtlilizationService(),],}).compile();

    apiHealthIndicator = module.get<ApiHealthIndicator>(ApiHealthIndicator);

    httpService = module.get<HttpService>(HttpService);
    dependencyUtlilizationService = module.get<DependencyUtlilizationService>(
      DependencyUtlilizationService,);
  });

  it('should be defined',() => {
    expect(apiHealthIndicator).toBeDefined();
  });

  it('isHealthy should return status as true when pingCheck return true',() => {
    jest
      .spyOn(dependencyUtlilizationService,'isRecentlyUsed')
      .mockReturnValue(true);

    const result = apiHealthIndicator.isHealthy(dnsList);

    result.then(response =>
      expect(response['domain_api'].status).toBe(HealthStatus.pass),);
  });
  it('isHealthy should return status as false when pingCheck return false','isRecentlyUsed')
      .mockReturnValue(false);

    jest.spyOn(httpService,'request').mockImplementation(config => {
      throw new Error('could not call api');
    });

    const result = apiHealthIndicator.isHealthy(dnsList);

    result
      .then(response => {
        expect(response['domain_api'].status).toBe(HealthStatus.fail);
      })
      .catch(reject => {
        expect(reject['domain_api'].status).toBe(HealthStatus.fail);
      });
  });
});

wangyirenhaha 回答:Nodejs Typescript笑话单元测试覆盖率显示了一些要覆盖的代码

看起来您应该在初始化单元测试之前定义状态,尝试使用console.log捕获更多日志,对于第二个测试,添加了catch块以确保您捕获了失败

本文链接:https://www.f2er.com/3056452.html

大家都在问