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

使用--findRelatedTests与lint-staged时Jest无法匹配测试用例

问题原因分析

你的Jest配置中roots仅指向测试文件目录,未包含源文件所在的apps/${currentTestDirectory}/src等目录,导致Jest无法扫描到被修改的源文件,自然无法找到与之关联的测试用例。同时,测试文件与源文件的路径映射关系需要匹配,才能让--findRelatedTests正确关联。

解决方案

1. 调整Jest的roots配置

修改jest.config.js中的roots字段,加入源文件所在目录,让Jest能扫描到被修改的文件:

roots: [
  `<rootDir>/tests/__tests__/${currentTestDirectory}`,
  `<rootDir>/apps/${currentTestDirectory}/src`,
  // 如果有其他源目录(如core、shared),也需添加
  `<rootDir>/core`,
  `<rootDir>/shared`
],

2. 确保测试文件路径与源文件对应

保证测试文件的路径和命名与源文件镜像匹配:

  • 源文件:apps/admin/src/pages/login/index.tsx
  • 对应测试文件:tests/__tests__/admin/pages/login/index.test.tsx(或.spec.tsx)

这样Jest的--findRelatedTests能通过文件名和路径直接关联到对应测试。

3. 优化lint-staged传递路径的方式(可选)

如果Jest仍无法识别绝对路径,可以修改.lintstagedrc,将绝对路径转为相对路径传递:

{
  "**/*.+(ts|tsx|js)": [
    "eslint",
    "prettier --write",
    "git diff --name-only --cached | grep -E '\\.(ts|tsx|js)$' | xargs npm run test:staged --"
  ]
}

同时保留package.json中的脚本配置:

"scripts": {
  "test:staged": "CI=true node scripts/test.js --bail --findRelatedTests"
}

4. 确认currentTestDirectory的动态取值(关键)

确保currentTestDirectory变量能根据被修改的文件动态切换为对应值(如修改admin目录文件时,变量值为admin)。如果该变量是静态固定的,会导致其他目录的文件修改时也无法找到对应测试。你可以通过脚本逻辑根据暂存文件路径自动设置这个变量,或者使用Jest的多项目配置来处理不同目录的测试。

验证修改

修改完成后,尝试修改apps/admin/src/pages/login/index.tsx并执行git commit -am "test",此时Jest应该能找到对应的测试用例并执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:05:39