VSCode monorepo下Jest测试自动匹配最近父目录cwd方法
问题背景
当前采用monorepo架构,各独立项目子目录下均存放独立的jest.config.js与package.json文件,目录结构示例如下:
items/thing/ items/other/ items/something/
在VSCode中聚焦测试文件时,原有launch.json配置仅支持固定在单个子目录(如items/thing/)下运行测试,配置示例:
{ "name": "Jest (this file)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/items/thing", "runtimeArgs": [ "--inspect-brk", "${workspaceFolder}/node_modules/.bin/jest", "${relativeFile}" ] }
切换到其他子目录(如items/other/)运行测试时,必须手动修改cwd字段为对应子目录路径,操作效率低。需求是实现cwd自动绑定到包含jest.config.js、package.json配置文件的最近父目录,无需反复调整launch.json配置。
可行解决方案
方案1:利用Jest原生配置查找能力,改写launch配置
Jest执行时默认会从传入的测试文件路径向上递归遍历父目录,自动定位最近的jest.config.js或声明了jest字段的package.json作为运行根目录,不需要手动指定固定cwd。修改后的配置如下:{ "name": "Jest (auto match root)", "type": "node", "request": "launch", "cwd": "${fileDirname}", "runtimeArgs": [ "--inspect-brk", "${workspaceFolder}/node_modules/.bin/jest", "${file}" ], "console": "integratedTerminal" }特殊情况处理:如果子项目的jest依赖安装在子目录而非工作区根目录,将jest路径替换为子项目下的对应路径即可;如果出现根目录识别错误,在对应子项目的
jest.config.js中显式声明rootDir: __dirname即可强制锁定运行根目录。方案2:预配置多套子项目启动项
如果子项目目录固定,可直接在launch.json中为每个子项目编写独立的启动配置,调试时在调试面板下拉选择对应项即可,无需反复修改配置字段,示例:[ { "name": "Jest: thing", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/items/thing", "runtimeArgs": ["--inspect-brk", "${workspaceFolder}/node_modules/.bin/jest", "${relativeFile}"] }, { "name": "Jest: other", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/items/other", "runtimeArgs": ["--inspect-brk", "${workspaceFolder}/node_modules/.bin/jest", "${relativeFile}"] }, { "name": "Jest: something", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/items/something", "runtimeArgs": ["--inspect-brk", "${workspaceFolder}/node_modules/.bin/jest", "${relativeFile}"] } ]方案3:使用Jest官方插件实现零配置
安装VSCode的Jest官方插件后,插件会自动扫描monorepo下所有子目录的jest配置,点击测试文件、测试用例旁的运行/调试按钮时,会自动切换到对应子项目的工作目录执行,完全不需要手动编写launch.json配置,同时支持断点调试、测试结果实时预览等能力。
内容的提问来源于stack exchange,提问作者Guy

