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

Mocha测试运行器是否支持仅重跑上一次失败的测试?

Mocha 仅运行上次失败测试的方案

好问题!Mocha 本身并没有内置的专属选项直接让你只运行上一次执行失败的测试,但有几种简便的实现方式刚好能满足你“修复后验证失败用例”的需求——完全不需要重试不稳定测试,就是精准跑上次挂了的那些测试。

方法一:手动用 --grep 筛选(适合小批量失败)

当你第一次跑测试出现失败后,Mocha 会在终端输出里清晰列出每个失败测试的完整名称,比如 UserService should update user email。你可以直接用 --grep 参数指定要跑的测试:

mocha --grep "UserService should update user email"

如果有多个失败测试,用竖线 | 分隔多个测试名称即可:

mocha --grep "TestA|TestB|TestC"

这种方式不需要额外工具,适合失败测试数量不多的场景。

方法二:用 mocha-last-failed 插件自动记录(最省心)

这个第三方插件会自动帮你记录上次失败的测试列表,完全不用手动操作:

  1. 先安装插件:
npm install mocha-last-failed --save-dev
  1. 运行测试时加上 --require mocha-last-failed 参数:
mocha --require mocha-last-failed
  • 如果上次有失败测试,它会自动只跑那些失败的用例;
  • 如果这次跑全部通过,下次再用这个命令就会恢复成运行所有测试。

方法三:自定义脚本实现(无依赖方案)

如果你不想装插件,可以自己写个简单的 Node 脚本来实现:

  1. 先让 Mocha 把测试结果输出为 JSON 文件:
mocha --reporter json > test-results.json
  1. 写一个小脚本(比如 run-failed-tests.js):
const fs = require('fs');
const { execSync } = require('child_process');

try {
  const results = JSON.parse(fs.readFileSync('./test-results.json', 'utf8'));
  const failedTests = results.failures.map(test => test.title.replace(/"/g, '\\"'));
  
  if (failedTests.length === 0) {
    console.log('No failed tests from last run, running all tests...');
    execSync('mocha', { stdio: 'inherit' });
  } else {
    const grepPattern = failedTests.join('|');
    console.log(`Running ${failedTests.length} failed tests...`);
    execSync(`mocha --grep "${grepPattern}"`, { stdio: 'inherit' });
  }
} catch (err) {
  console.log('Could not read test results, running all tests...');
  execSync('mocha', { stdio: 'inherit' });
}
  1. 运行这个脚本即可自动执行上次失败的测试:
node run-failed-tests.js

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:53:34