如何在Vitest中获取兼容Jest的JSON格式覆盖率汇总?
解决Vitest生成兼容Jest格式的JSON覆盖率汇总问题
要让Vitest输出能被MishaKav/jest-coverage-comment识别的Jest兼容JSON覆盖率,按以下步骤操作:
1. 确认使用正确的覆盖率工具
Vitest官方推荐的@vitest/coverage-v8(基于V8引擎)支持生成Jest风格的覆盖率报告,若未安装先执行:
npm install -D @vitest/coverage-v8
2. 调整Vitest配置文件
在vitest.config.ts(或.js)中配置coverage选项,指定生成匹配Jest结构的汇总报告:
import { defineConfig } from 'vitest/config' export default defineConfig({ test: { coverage: { provider: 'v8', reporter: [ 'text', 'json-summary', // 生成Jest兼容的汇总JSON 'json' ], jsonSummaryReporter: { outputFile: 'coverage/coverage-summary.json' // 指定汇总文件路径 }, reportsDirectory: 'coverage' } } })
3. 适配coverage-final.json结构(可选)
若直接使用coverage/coverage-final.json仍报错,是因为Vitest该文件的汇总数据在summary字段下,而Jest需要的是顶层total字段。可添加转换脚本:
在package.json中新增脚本:
{ "scripts": { "posttest": "node scripts/convert-coverage.js" } }
创建scripts/convert-coverage.js:
const fs = require('fs') const path = require('path') const coveragePath = path.join(__dirname, '../coverage/coverage-final.json') const outputPath = path.join(__dirname, '../coverage/jest-compatible-coverage.json') const coverage = JSON.parse(fs.readFileSync(coveragePath, 'utf8')) const jestCompatible = { total: coverage.summary } fs.writeFileSync(outputPath, JSON.stringify(jestCompatible, null, 2))
测试完成后,使用coverage/jest-compatible-coverage.json作为Action的coverage-path参数即可。
4. 验证GitHub Action配置
确保Action中指定正确的文件路径:
- name: Comment coverage uses: MishaKav/jest-coverage-comment@v1 with: coverage-path: coverage/jest-compatible-coverage.json junit-xmlpath: coverage/junit.xml
内容的提问来源于stack exchange,提问作者Toru Uetani
相关产品推荐
相关产品推荐

