配置VS Code调试Jest和Pytest需设置launch.json:Jest使用node类型,runtimeExecutable为npm,加--runInBand避免并行;Pytest用python类型,module为pytest,args含${file}、-s、-v,确保正确运行测试并输出信息。
在 vs code 中调试 jest 或 pytest 测试非常方便,只要正确配置启动设置,就可以直接在编辑器中设置断点、查看变量和单步执行。下面是针对这两个常用测试框架的调试配置方法。
调试 Jest(JavaScript/Node.js)
要在 VS Code 中调试 Jest 测试,需要配置 launch.json 文件,让调试器能正确启动 Jest 并附加到 Node.js 进程。
步骤:- 确保项目根目录已安装 Jest,且
package.json中有类似"test": "jest"的脚本 - 在项目根目录创建
.vscode/launch.json文件(如果不存在) - 添加以下配置来启动 Jest 调试
launch.json 配置示例(Jest):
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Jest Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "test", "--", "--runInBand"],
"console": "integratedTerminal",
"port": 9229,
"autoAttachChildProcesses": true,
"skipFiles": ["/**"]
}
]
}
说明:
-
--runInBand:防止 Jest 并行运行测试,确保调试器能正确捕获流程 -
console: "integratedTerminal":在终端中运行,便于查看输出 - 设置断点后按 F5 启动调试,即可进入测试代码
调试 Pytest(Python)
VS Code 支持使用 Python 扩展轻松调试 Pytest,前提是已安装 Python 插件并配置好解释器。
步骤:- 确保已安装 pytest:
pip install pytest - 在项目中打开一个测试文件(如
test_example.py) - 创建或修改
.vscode/launch.json
launch.json 配置示例(Pytest):
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"${file}",
"-s",
"-v"
],
"console": "integratedTerminal",
"justMyCode": true
}
]
}
说明:
-
${file}表示当前打开的测试文件,可改为具体路径或留空运行全部测试 -
-s允许打印输出(如 print 语句) -
-v提供详细日志 - 使用 Python 调试器(需安装
debugpy,通常随 Python 扩展自动安装)
保存配置后,在测试函数中点击“Run and Debug”按钮或按 F5,即可开始调试。
小贴士
- 确保工作区是项目根目录,以便正确解析模块路径
- 若使用虚拟环境(Python),在
launch.json中指定python路径:"python": "/path/to/venv/bin/python" - Jest 用户可考虑使用
vscode-jest插件实现自动运行和高亮 - 调试时关注输出面板中的“Debug Console”或“Terminal”信息
基本上就这些。配置一次后,每次调试只需打开测试文件、设好断点、点运行,效率提升明显。










