调试
TIP
调试测试时,您可能希望使用 --test-timeout
CLI 参数,以防止在断点处暂停时测试超时。
VS Code
在 VS Code 中调试测试的快捷方式是使用 JavaScript Debug Terminal
。打开一个新的 JavaScript Debug Terminal
并直接运行 npm run test
或 vitest
。此方法适用于在 Node.js 环境中运行的任何代码,因此也适用于大多数 JavaScript 测试框架。
您还可以添加一个专门的启动配置,以便在 VS Code 中调试测试文件:
{
// 更多信息请访问:https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Current Test File",
"autoAttachChildProcesses": true,
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"args": ["run", "${relativeFile}"],
"smartStep": true,
"console": "integratedTerminal"
}
]
}
然后,在调试选项卡中,确保选中“Debug Current Test File”(调试当前测试文件)选项。接着,您可以打开要调试的测试文件,按 F5 开始调试。
浏览器模式
要调试 Vitest 浏览器模式,可以在 CLI 中传入 --inspect
或 --inspect-brk
参数,或者在您的 Vitest 配置中定义:
vitest --inspect-brk --browser --no-file-parallelism
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
inspectBrk: true,
fileParallelism: false,
browser: {
name: 'chromium',
provider: 'playwright',
},
},
});
默认情况下,Vitest 将使用端口 9229
作为调试端口。您可以通过在 --inspect-brk
中传递值来覆盖该端口:
vitest --inspect-brk=127.0.0.1:3000 --browser --no-file-parallelism
可以使用以下 VS Code 复合配置 来启动 Vitest 并在浏览器中附加调试器:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Run Vitest Browser",
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"console": "integratedTerminal",
"args": ["--inspect-brk", "--browser", "--no-file-parallelism"]
},
{
"type": "chrome",
"request": "attach",
"name": "Attach to Vitest Browser",
"port": 9229
}
],
"compounds": [
{
"name": "Debug Vitest Browser",
"configurations": ["Attach to Vitest Browser", "Run Vitest Browser"],
"stopAll": true
}
]
}
IntelliJ IDEA
创建一个 Vitest 运行配置。使用以下设置在调试模式下运行所有测试:
设置 | 值 |
---|---|
工作目录 | /path/to/your-project-root |
然后以调试模式运行此配置。IDE 将在编辑器中设置的 JavaScript/TypeScript 断点处停止。
Node Inspector,例如 Chrome DevTools
Vitest 还支持在没有 IDE 的情况下调试测试。然而,这要求测试不能并行运行。使用以下命令之一来启动 Vitest:
# 在单个工作线程中运行
vitest --inspect-brk --pool threads --poolOptions.threads.singleThread
# 在单个子进程中运行
vitest --inspect-brk --pool forks --poolOptions.forks.singleFork
# 在浏览器模式中运行
vitest --inspect-brk --browser --no-file-parallelism
如果您使用的是 Vitest 1.1 或更高版本,您也可以只提供 --no-file-parallelism
标志:
# 如果 pool 类型未知
vitest --inspect-brk --no-file-parallelism
Vitest 启动后,它将停止执行并等待您打开可连接到 Node.js inspector 的开发工具。您可以通过在浏览器中打开 chrome://inspect
来使用 Chrome DevTools。
在观察模式下,您可以使用 --poolOptions.threads.isolate false
选项,在测试重新运行时保持调试器处于打开状态。