3. Generating tests
介绍
- 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.
You will learn
Running Codegen
请使用 codegen 命令来运行测试生成器,随后输入你想要生成测试的网站的网址。网址为可选项,若未提供则可直接在浏览器窗口中添加。
playwright codegen demo.playwright.dev/todomvc
Recording a test
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:
-
Actions like click or fill by interacting with the page
-
Assertions by clicking a toolbar icon, then clicking a page element to assert against. You can choose:
- 'assert visibility' to assert that an element is visible
- 'assert text' to assert that an element contains specific text
- 'assert value' to assert that an element has a specific value
-
录制过程及选择脚本语言

- 拷贝脚本到代码编辑器,执行脚本

Generating locators
You can generate locators with the test generator.
Press the 'Record' button to stop recording and the 'Pick Locator' button will appear
Click the 'Pick Locator' button and hover over elements in the browser window to see the locator highlighted underneath each element
Click the element you want to locate and the code for that locator will appear in the locator playground next to the Pick Locator button
Edit the locator in the locator playground to fine-tune it and see the matching element highlighted in the browser window
Use the copy button to copy the locator and paste it into your code
picking a locator
Emulation
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

浙公网安备 33010602011771号