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

如何通过Jest CLI仅运行指定子文件夹内的测试?

解决方案

方法1:使用--testPathPattern(推荐,更直观)

Jest的--testPathPattern参数支持glob路径模式,完全匹配你要找的src/**/__unit__/**/*.spec.ts文件,直接执行以下命令即可:

npx jest --testPathPattern "src/**/__unit__/**/*.spec.ts"

如果要在package.json的scripts中配置,写法如下(注意转义双引号):

{
  "scripts": {
    "test:unit": "jest --testPathPattern \"src/**/__unit__/**/*.spec.ts\"",
    "test:integration": "jest --testPathPattern \"src/**/__integration__/**/*.spec.ts\""
  }
}

方法2:修正--testRegex的正则表达式

如果坚持要用--testRegex,需要把glob模式转换成正确的正则表达式(--testRegex接受正则而非glob),正确命令如下:

npx jest --testRegex "^src/.*/__unit__/.+\.spec\.ts$"

正则说明:

  • ^src/:确保路径从项目根的src/开始
  • .*/:匹配__unit__所在目录之前的任意层级子目录
  • __unit__/:精确匹配单元测试目录
  • .+\.spec\.ts$:匹配以.spec.ts结尾的任意文件名

原命令失败的原因

你之前的命令npx jest --testRegex "src\**\__unit__\**\*.spec.ts"存在两个问题:

  1. --testRegex要求传入正则表达式,但你用的是glob路径格式,语法不兼容
  2. 反斜杠\在正则中是转义符,\**会被解析为无效规则,路径分隔应使用正斜杠/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:40:57