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

如何将参数传递至Lerna exec命令实现统一测试传参?

解决Lerna Monorepo中测试命令参数传递问题

我之前也碰到过一模一样的场景——用Lerna管理monorepo,根目录和子包的测试都基于Jest,但lerna exec默认不会把外层的命令参数传递给子包的yarn test。要实现yarn test -t=Pattern或yarn test --updateSnapshot时参数同时传给根目录和所有子包的测试,写个简单的shell脚本就能搞定:

步骤1:创建统一的测试执行脚本

在项目根目录新建scripts/run-all-tests.sh文件,内容如下:

#!/bin/bash

# 执行根目录的测试,原样传递所有命令参数
yarn test:root "$@"

# 执行所有子包的测试,通过lerna exec传递参数(--用于分隔Lerna参数和子命令参数)
lerna exec -- yarn test "$@"

给脚本添加执行权限:

chmod +x scripts/run-all-tests.sh

步骤2:修改package.json中的scripts

把原来的test命令替换为调用这个脚本,保留原有的test:root(它已经支持$@接收参数):

{
  "scripts": {
    "test": "./scripts/run-all-tests.sh",
    "test:root": "jest", // 你的根目录Jest命令,保持不变
    "test:packages": "lerna exec -- yarn test" // 可选保留,用于单独跑子包测试
  }
}

为什么这样有效?

  • "$@"会将你执行yarn test时传入的所有参数原样、正确地传递给每个测试命令,包括带空格或特殊字符的参数都能正常处理。
  • Lerna的exec命令后加上--是关键:它告诉Lerna,--后面的参数不属于Lerna本身,而是要传递给每个子包中执行的yarn test命令。

测试验证

现在执行你需要的命令,参数会同时作用于根目录和所有子包:

  • 匹配测试用例:yarn test -t="UserLogin"
  • 更新快照:yarn test --updateSnapshot

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:18:32