测试调试
🌐 Test Debugging
使用 CLI 以交互方式调试 Playwright 测试失败。
🌐 Use the CLI to debug Playwright test failures interactively.
正在连接到已暂停的测试
🌐 Connecting to a paused test
用 --debug=cli 运行测试。后台执行——测试保持暂停状态,并在你工作时保持浏览器打开。
🌐 Run the test with --debug=cli. Do it in the background — the test stays paused and holds the
browser open while you work.
PLAYWRIGHT_HTML_OPEN=never npx playwright test tests/checkout.spec.ts --debug=cli
测试在开始时会暂停,并打印要附加的会话名称:
🌐 The test pauses at the start and prints the session name to attach to:
### The test is currently paused at the start
### Debugging Instructions
- Run "playwright-cli attach tw-a3f19c" to attach to this test
playwright-cli attach tw-a3f19c
PLAYWRIGHT_HTML_OPEN=never 会阻止运行结束后 HTML 报告自动弹出。
浏览页面
🌐 Exploring the page
playwright-cli snapshot # see current state
playwright-cli find "Place order" # locate one element on a big page
playwright-cli console error # check for errors
playwright-cli requests --filter="/api/"
playwright-cli eval "() => document.title"
playwright-cli screenshot --filename=debug-state.png
控制执行
🌐 Controlling execution
| 命令 | 描述 |
|---|---|
resume | 继续运行 |
step-over | 跳过测试中的下一个调用 |
pause-at <file>:<line> | 运行到某个位置并在那里暂停 |
playwright-cli pause-at checkout.spec.ts:42
playwright-cli step-over
playwright-cli resume
因为测试一开始就暂停了,pause-at 通常是最快的方式:直接跳到问题最可能出现的那一行。
🌐 Because the test is paused at the very start, pause-at is usually the fastest way in: jump
straight to the line where the problem is most likely to be.
阅读生成的代码
🌐 Reading the generated code
每个 playwright-cli 操作都会打印出对应的 Playwright TypeScript。这就是你粘回测试中的修复 —— 大多数情况下需要更新定位器或期望,但也可能是真正的应用错误。查看 Codegen & Highlighting。
🌐 Every playwright-cli action prints the equivalent Playwright TypeScript. That is the fix you paste
back into the test — most of the time a locator or an expectation needs updating, but it can also be
a genuine bug in the app. See Codegen & Highlighting.
工作流程:调查不稳定的测试
🌐 Workflow: investigating a flaky test
# 1. Run the failing test in the background
PLAYWRIGHT_HTML_OPEN=never npx playwright test tests/checkout.spec.ts --debug=cli
# 2. Connect
playwright-cli attach tw-a3f19c
# 3. Record a trace
playwright-cli tracing-start
# 4. Run to the suspect line
playwright-cli pause-at tests/checkout.spec.ts:42
playwright-cli snapshot
playwright-cli console
playwright-cli requests
# 5. Investigate at the failing step
playwright-cli screenshot --filename=before-failure.png
playwright-cli eval "() => document.querySelector('.spinner')?.style.display"
# 6. Save trace, then stop the background test run and re-run it
playwright-cli tracing-stop
完成后停止后台测试运行,然后重新运行测试以确认问题已修复。
🌐 Stop the background test run once you are done, then re-run the test to confirm the fix.