生成测试
介绍
🌐 Introduction
Playwright 可以自动生成测试,为开始测试提供快速方法。Codegen 会打开一个浏览器窗口进行交互,并打开 Playwright 检查器以记录、复制和管理生成的测试。
🌐 Playwright can generate tests automatically, providing a quick way to get started with testing. Codegen opens a browser window for interaction and the Playwright Inspector for recording, copying, and managing your generated tests.
你将学习
运行代码生成器
🌐 Running Codegen
使用 codegen 命令运行测试生成器,然后输入你想生成测试的网页 URL。URL 是可选的,如果省略,可以直接在浏览器窗口中添加。
🌐 Use the codegen command to run the test generator followed by the URL of the website you want to generate tests for. The URL is optional and can be added directly in the browser window if omitted.
npx playwright codegen demo.playwright.dev/todomvc
记录测试
🌐 Recording a test
运行 codegen 并在浏览器中执行操作。Playwright 会自动为你的交互生成代码。Codegen 会分析渲染后的页面,并推荐最佳定位器,优先考虑角色、文本和测试 ID 定位器。当多个元素匹配同一个定位器时,生成器会改进定位器以唯一识别目标元素,从而减少测试失败和不稳定性。
🌐 Run codegen and perform actions in the browser. Playwright generates code for your interactions automatically. Codegen analyzes the rendered page and recommends the best locator, prioritizing role, text, and test id locators. When multiple elements match a locator, the generator improves it to uniquely identify the target element, reducing test failures and flakiness.
使用测试生成器,你可以记录:
🌐 With the test generator you can record:
- 通过与页面交互执行单击或填充等操作
- 通过点击工具栏图标,然后点击页面元素进行断言。你可以选择:
'assert visibility'用于断言一个元素是可见的'assert text'用于断言一个元素包含特定文本'assert value'用于断言元素具有特定值

当你完成与页面的交互后,按下 'record' 按钮停止录制,并使用 'copy' 按钮将生成的代码复制到你的编辑器。
使用 'clear' 按钮清除代码并重新开始录制。完成后,关闭 Playwright 检查器窗口或停止终端命令。
🌐 Use the 'clear' button to clear the code and start recording again. Once finished, close the Playwright Inspector window or stop the terminal command.
想了解更多关于生成测试的信息,请查看我们关于Codegen的详细指南。
🌐 To learn more about generating tests, check out our detailed guide on Codegen.
生成定位器
🌐 Generating locators
你可以使用测试生成器生成定位器。
🌐 You can generate locators with the test generator.
- 按下
'Record'按钮停止录音,'Pick Locator'按钮将会出现 - 点击
'Pick Locator'按钮,并将鼠标悬停在浏览器窗口中的元素上,以查看每个元素下方高亮显示的定位器 - 点击你要定位的元素,该定位器的代码将显示在“选择定位器”按钮旁边的定位器演示区中。
- 在定位器测试区中编辑定位器进行微调,并在浏览器窗口中查看高亮显示的匹配元素
- 使用“复制”按钮复制定位器并将其粘贴到你的代码中。

模拟
🌐 Emulation
你可以使用模拟来为特定的视口、设备、颜色方案、地理位置、语言或时区生成测试。测试生成器还可以保留已认证的状态。查看Test Generator指南以了解更多信息。
🌐 You can generate tests using emulation for specific viewports, devices, color schemes, geolocation, language, or timezone. The test generator can also preserve authenticated state. Check out the Test Generator guide to learn more.
下一步是什么
🌐 What's Next