本指南介绍如何使用 Vitest 调试 Workers 测试。此功能在 @cloudflare/vitest-pool-workers v0.7.5 或更高版本中可用。
要开始调试,请使用以下命令运行 Vitest,并将调试器附加到端口 9229:
vitest --inspect --no-file-parallelism默认情况下,inspector 会在端口 9229 上打开。如果你需要使用其他端口(例如 3456),可以运行以下命令:
vitest --inspect=3456 --no-file-parallelism或者,你可以在 Vitest 配置文件中定义:
import { cloudflareTest } from "@cloudflare/vitest-pool-workers";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [
cloudflareTest({
// ...
}),
],
test: {
inspector: {
port: 3456,
},
},
});要在 Worker 测试中设置 VS Code 断点调试,请创建包含以下配置的 .vscode/launch.json 文件:
{
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Open inspector with Vitest",
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"console": "integratedTerminal",
"args": ["--inspect=9229", "--no-file-parallelism"]
},
{
"name": "Attach to Workers Runtime",
"type": "node",
"request": "attach",
"port": 9229,
"cwd": "/",
"resolveSourceMapLocations": null,
"attachExistingChildren": false,
"autoAttachChildProcesses": false
}
],
"compounds": [
{
"name": "Debug Workers tests",
"configurations": [
"Open inspector with Vitest",
"Attach to Workers Runtime"
],
"stopAll": true
}
]
}在 Run & Debug(运行和调试) 面板顶部选择 Debug Workers tests(调试 Workers 测试),以使用 Vitest 打开 inspector 并将调试器附加到 Workers 运行时。然后你可以在测试文件中添加断点并开始调试。