在 VS Code 中调试单元测试需先确保测试框架可正常运行,再配置 launch.json 并设置断点;支持 Jest、Vitest、Mocha、pytest 等,通过 --runInBand 等参数精准控制执行,实现断点、变量监视与步进调试。
在 vs code 中调试单元测试其实很直接,关键在于配置好 launch.json 并选对测试框架的运行方式。不用非得靠命令行跑完再猜哪行出错了——断点、变量监视、调用栈全都能实时看。
VS Code 调试器本身不执行测试,它依赖你项目中已配置好的测试命令(比如 Jest、Vitest、Mocha 或 pytest)。先确保你在终端里能正常运行测试:
npx jest --watch 能启动监听模式npx vitest 可进入交互式 UIpython -m pytest test_example.py -s 要能打印输出如果命令行都跑不起来,调试器也无从下手。顺便检查 package.json 的 test 脚本或 pyproject.toml 是否配置无误。
按 Ctrl+Shift+P(Windows/Linux)或 Cmd+Shift+P(macOS),输入 “Debug: Open launch.json”,选择对应环境(如 “Node.js” 或 “Python”)。然后添加一个配置项,例如 Jest:
{
"type": "node",
"request": "launch",
"name": "Debug Jest Tests",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand", "--no-cache"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
要点说明:
--runInBand 确保测试在当前进程串行执行,避免多线程干扰断点--no-cache 防止因缓存跳过修改后的代码runtimeExecutable 指向本地安装的 CLI,而非全局 jest
python 类型,设置 module: "pytest",并加 "args": ["-s", "test_file.py"]
打开你的 test_*.js 或 test_*.py 文件,在想暂停的地方单击左侧空白处设断点(红点出现即可)。接着:
Ctrl+Shift+D 打开调试面板VS Code 会自动启动测试进程,命中断点后暂停。此时你可以查看变量值、执行表达式、逐行步入(F11)、步过(F10)、继续(F5),和调试普通代码完全一致。
不想每次全量跑?可以在 args 里加过滤参数:
"args": ["--runInBand", "test/utils.test.js"] 或 "--testNamePattern=should handle null input"
"args": ["--run", "test/api.test.ts"]
"args": ["-k", "test_login", "test_auth.py"]
也可以在测试代码里临时加 it.only(Jest/
Vitest)或 pytest.mark.focus(需插件),让调试更聚焦。
基本上就这些。配置一次,后续点几下就能边跑测试边查逻辑,比反复 console.log 高效得多。