为什么 Jest 中的 "Branch" 测试覆盖率显示为 0%?

Why "Branch" test coverage in Jest shows 0% coverage?

我的一个测试覆盖率如下:

我看到总共 3 行:16、27 和 38 在未覆盖的行下。我通过查看 coverage/Icov-report/index.html(改进单元测试的 WIP)来确认这一点。

缺少 3 行覆盖会导致分支覆盖为 0% 吗?我希望有一些东西而不是 0%,但我正在学习 Jest,所以不确定。

service.ts

import { injectable } from 'inversify';
import { createLogger, format, Logger } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import fs from 'fs';

const logDir = 'logs';

@injectable()
export default class LoggerService {
  private readonly winstonLogger: Logger;

  private static loggerService: LoggerService;

  constructor() {
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir);
    }

    const dailyRotateFileTransport = new DailyRotateFile({
      filename: `${logDir}/%DATE%-results.log`,
      datePattern: 'YYYY-MM-DD',
    });

    this.winstonLogger = createLogger({
      format: format.combine(
        format.timestamp(),
        format.printf((info) => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message)}`),
      ),
      transports: [
        dailyRotateFileTransport,
      ],
      exitOnError: false,
    });
  }

  static get Instance() {
    if (this.loggerService) {
      return this.loggerService;
    }
    this.loggerService = new LoggerService();
    return this.loggerService;
  }

  public get logger() {
    return this.winstonLogger;
  }
}

service.spec.ts

const logger = {
  debug: jest.fn(),
  log: jest.fn(),
};

// trying to mock createLogger to return a specific logger instance
jest.mock('winston', () => ({
  format: {
    combine: jest.fn(),
    timestamp: jest.fn(),
    printf: jest.fn(),
  },
  createLogger: jest.fn().mockReturnValue(logger),
  transports: {
    File: jest.fn(),
  },
}));

import 'reflect-metadata';
import * as winston from 'winston';
import LoggerService from '../logger.service';

describe('loggerService', () => {
  let loggerMock: winston.Logger;

  afterAll(() => {
    jest.resetModules();
    jest.resetAllMocks();
  });

  it('logger function called', () => {
    const mockCreateLogger = jest.spyOn(winston, 'createLogger');
    const loggingService: LoggerService = LoggerService.Instance;
    loggerMock = mockCreateLogger.mock.instances[0];
    expect(loggingService).toBeInstanceOf(LoggerService);
    expect(loggingService).toBeDefined();
    expect(mockCreateLogger).toHaveBeenCalled();
    
    logger.log('debug', 'test log debug');
    expect(logger.log).toHaveBeenCalled();

    loggingService.logger.debug('debug message');
    expect(logger.debug).toHaveBeenCalledTimes(1);
  });
});


看起来 0% 意味着您错过了测试 所有 if 肯定属于类别 Branch.
尝试为 if 之一添加测试,看看 % Branch 是否会变成 50%