You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程获取Jest执行的总测试数并存储到变量中

从Jest执行输出提取总测试数并存储到变量

以下几种方法可实现需求:

1. 命令行脚本方式(Bash)

直接通过Jest的标准输出,用文本处理工具提取数字并存储到变量:

方法一:grep + awk

# 执行Jest并捕获总测试数
TOTAL_TESTS=$(jest | grep 'Tests:' | awk '{print $4}')
# 验证变量值
echo $TOTAL_TESTS

说明:grep 'Tests:'筛选出包含测试统计的行,awk '{print $4}'提取该行中对应总测试数的字段(对应示例行里的第二个224)。

方法二:sed正则匹配

TOTAL_TESTS=$(jest | sed -n 's/^Tests:.* \([0-9]*\) total$/\1/p')
echo $TOTAL_TESTS

说明:sed通过正则匹配捕获行末尾的总测试数字,直接提取输出。

2. 自定义Jest Reporter(编程方式)

如果需要在Node.js环境中直接获取测试数据,可以编写自定义Reporter:

  1. 创建custom-reporter.js文件:
class CustomReporter {
  onRunComplete(_, results) {
    // results.numTotalTests 即为总测试数
    const totalTests = results.numTotalTests;
    // 可将数值写入文件、打印或传递给其他统计逻辑
    console.log(`总测试数:${totalTests}`);
    require('fs').writeFileSync('total-tests.log', totalTests.toString());
  }
}

module.exports = CustomReporter;
  1. 执行Jest时指定该Reporter:
jest --reporters=default --reporters=./custom-reporter.js

执行后,总测试数会被写入total-tests.log文件,后续可直接读取该文件进行统计。

补充说明:jest --listTests仅用于列出测试文件路径,无法统计测试用例总数;覆盖率报告聚焦代码覆盖情况,也不包含测试用例的总数量。

内容的提问来源于stack exchange,提问作者slotdp02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:08:14