从Jest合并JSON覆盖报告

swvgeqrz  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(116)

我目前正在收集Lerna monorepo内模块的覆盖范围。在每个package.json中,我运行jest --coverage --json --outputFile someDir
这将创建多个JSON报告,其模式如下:

{
  "numFailedTestSuites": 0,
  "numFailedTests": 0,
  "numPassedTestSuites": 0,
  "numPassedTests": 18,
  "numPendingTestSuites": 0,
  "numPendingTests": 0,
  "numRuntimeErrorTestSuites": 0,
  "numTodoTests": 0,
  "numTotalTestSuites": 8,
  "numTotalTests": 18,
  "openHandles": [],
  "snapshot": {
    // ...
  }
  // ...
}

字符串
我想将所有这些输出合并到根目录下的一个JSON报告中。我的主要目标是通过GitHub Actions工作流收集和报告覆盖率(需要Jest的--json报告)。
我一直在尝试使用伊斯坦布尔来合并它,然而,它似乎只适用于覆盖图,因此与coverage-final.json文件产生。
当我尝试从生成的JSON报告中合并时,我得到:

Error: Coverage must be initialized with a path or an object


我假设这是因为模式不正确。

3qpi33ja

3qpi33ja1#

为了将Jest中的多个JSON报告合并到一个报告中,您可以使用伊斯坦布尔提供的istanbul-merge工具。但是,正如您提到的,伊斯坦布尔通常使用coverage map和coverage-final.json文件。
要合并Jest JSON报告,您需要将它们转换为伊斯坦布尔兼容的覆盖率格式。以下是您可以遵循的示例工作流:
通过在项目的根目录中运行以下命令来安装所需的软件包:

npm install --save-dev istanbul istanbul-merge

字符串
在项目的package.json文件中创建一个新脚本来处理合并过程。在scripts部分下添加以下脚本:

"scripts": {
  "merge-coverage": "node merge-coverage.js"
}


在项目的根目录中创建一个名为merge-coverage.j s的新文件。此文件将包含合并JSON报告的代码。将以下代码添加到merge-coverage.js

const fs = require('fs');
const istanbul = require('istanbul');
const merge = require('istanbul-merge');

const mergedReportPath = './coverage/merged-report.json'; // Adjust the output path as needed
const reportPaths = [
  // Specify the paths of your individual Jest JSON reports
  './path/to/report1.json',
  './path/to/report2.json',
  // Add more report paths as needed
];

// Load the reports
const reports = reportPaths.map((reportPath) => JSON.parse(fs.readFileSync(reportPath, 'utf8')));

// Merge the reports
const mergedReport = merge.createCoverageMap();

for (const report of reports) {
  const coverageMap = istanbul.createCoverageMap(report);
  mergedReport.merge(coverageMap);
}

// Write the merged report to a file
fs.writeFileSync(mergedReportPath, JSON.stringify(mergedReport.toJSON(), null, 2));

console.log('Coverage reports merged successfully!');


通过执行以下命令运行合并脚本:

npm run merge-coverage


这将执行merge-coverage脚本并在指定的mergedReportPath上生成合并的覆盖率报告。
您现在可以将合并的报告文件(merged-report.json)用于GitHub Actions工作流或任何其他覆盖率报告目的。
通过以上步骤,您应该能够使用Istanbul将各个Jest JSON报告合并为单个JSON报告,并为您的GitHub Actions工作流生成所需的覆盖率报告。
希望这对你有用。

相关问题