测试生成器
介绍
¥Introduction
当你在浏览器中执行操作时,Playwright 能够为你生成测试,这是快速开始测试的好方法。Playwright 将查看你的页面并找出最佳定位器,优先考虑 角色、文本和测试 ID 定位器。如果生成器找到与定位器匹配的多个元素,它将改进定位器,使其具有唯一标识目标元素的弹性。
¥Playwright comes with the ability to generate tests for you as you perform actions in the browser and is a great way to quickly get started with testing. Playwright will look at your page and figure out the best locator, prioritizing role, text and test id locators. If the generator finds multiple elements matching the locator, it will improve the locator to make it resilient that uniquely identify the target element.
使用 Playwright 检查器生成测试
¥Generate tests with the Playwright Inspector
运行 codegen
命令时,将打开两个窗口,一个是浏览器窗口,你可以在其中与要测试的网站进行交互,另一个是 Playwright Inspector 窗口,你可以在其中记录测试,然后将它们复制到编辑器中。
¥When running the codegen
command two windows will be opened, a browser window where you interact with the website you wish to test and the Playwright Inspector window where you can record your tests and then copy them into your editor.
运行代码生成器
¥Running Codegen
使用 codegen
命令运行测试生成器,后跟要为其生成测试的网站的 URL。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 you can always run the command without it and then add the URL directly into the browser window instead.
playwright codegen demo.playwright.dev/todomvc
记录测试
¥Recording a test
运行 codegen
命令并在浏览器窗口中执行操作。Playwright 将为用户交互生成代码,你可以在 Playwright 检查器窗口中看到这些代码。完成录制测试后,停止录制并按复制按钮将生成的测试复制到编辑器中。
¥Run the codegen
command and perform actions in the browser window. Playwright will generate the code for the user interactions which you can see in the Playwright Inspector window. Once you have finished recording your test stop the recording and press the copy button to copy your generated test into your editor.
使用测试生成器,你可以记录:
¥With the test generator you can record:
-
只需与页面交互即可执行点击或填充等操作
¥Actions like click or fill by simply interacting with the page
-
通过单击工具栏中的图标之一,然后单击页面上要断言的元素来进行断言。你可以选择:
¥Assertions by clicking on one of the icons in the toolbar and then clicking on an element on the page to assert against. You can choose:
-
'assert visibility'
断言元素可见¥
'assert visibility'
to assert that an element is visible -
'assert text'
断言元素包含特定文本¥
'assert text'
to assert that an element contains specific text -
'assert value'
断言某个元素具有特定值¥
'assert value'
to assert that an element has a specific value
-
完成与页面的交互后,按录制按钮停止录制,并使用复制按钮将生成的代码复制到编辑器。
¥When you have finished interacting with the page, press the record button to stop the recording and use the copy button to copy the generated code to your editor.
使用清除按钮清除代码以重新开始录制。完成后,关闭 Playwright 检查器窗口或停止终端命令。
¥Use the clear button to clear the code to start recording again. Once finished, close the Playwright inspector window or stop the terminal command.
生成定位器
¥Generating locators
你可以使用测试生成器生成 locators。
¥You can generate locators with the test generator.
-
按
'Record'
按钮停止录音,然后会出现'Pick Locator'
按钮。¥Press the
'Record'
button to stop the recording and the'Pick Locator'
button will appear. -
单击
'Pick Locator'
按钮,然后将鼠标悬停在浏览器窗口中的元素上,即可查看每个元素下方高亮的定位器。¥Click on the
'Pick Locator'
button and then hover over elements in the browser window to see the locator highlighted underneath each element. -
要选择定位器,请单击要定位的元素,该定位器的代码将显示在“选择定位器”按钮旁边的字段中。
¥To choose a locator, click on the element you would like to locate and the code for that locator will appear in the field next to the Pick Locator button.
-
然后,你可以在此字段中编辑定位器以对其进行微调,或使用复制按钮将其复制并粘贴到代码中。
¥You can then edit the locator in this field to fine tune it or use the copy button to copy it and paste it into your code.
模拟
¥Emulation
你可以使用测试生成器通过模拟生成测试,以便为特定视口、设备、配色方案生成测试,以及模拟地理位置、语言或时区。测试生成器还可以生成测试,同时保留经过身份验证的状态。
¥You can use the test generator to generate tests using emulation so as to generate a test for a specific viewport, device, color scheme, as well as emulate the geolocation, language or timezone. The test generator can also generate a test while preserving authenticated state.
模拟视口大小
¥Emulate viewport size
Playwright 打开一个浏览器窗口,其视口设置为特定的宽度和高度,并且没有响应,因为测试需要在相同的条件下运行。使用 --viewport
选项生成具有不同视口大小的测试。
¥Playwright opens a browser window with its viewport set to a specific width and height and is not responsive as tests need to be run under the same conditions. Use the --viewport
option to generate tests with a different viewport size.
playwright codegen --viewport-size="800,600" playwright.dev

模拟设备
¥Emulate devices
使用 --device
选项模拟移动设备时记录脚本和测试,该选项设置视口大小和用户代理等。
¥Record scripts and tests while emulating a mobile device using the --device
option which sets the viewport size and user agent among others.
playwright codegen --device="iPhone 13" playwright.dev

模拟配色方案
¥Emulate color scheme
记录脚本和测试,同时使用 --color-scheme
选项模拟配色方案。
¥Record scripts and tests while emulating the color scheme with the --color-scheme
option.
playwright codegen --color-scheme=dark playwright.dev

模拟地理位置、语言和时区
¥Emulate geolocation, language and timezone
记录脚本和测试,同时使用 --timezone
、--geolocation
和 --lang
选项模拟时区、语言和位置。页面打开后:
¥Record scripts and tests while emulating timezone, language & location using the --timezone
, --geolocation
and --lang
options. Once the page opens:
-
接受 cookies
¥Accept the cookies
-
在右上角,单击“定位我”按钮以查看实际的地理位置。
¥On the top right, click on the locate me button to see geolocation in action.
playwright codegen --timezone="Europe/Rome" --geolocation="41.890221,12.492348" --lang="it-IT" bing.com/maps

保留经过身份验证的状态
¥Preserve authenticated state
运行 codegen
和 --save-storage
以在会话结束时保存 cookies、localStorage 和 IndexedDB 数据。这对于单独记录身份验证步骤并在稍后记录更多测试时重复使用非常有用。
¥Run codegen
with --save-storage
to save cookies, localStorage and IndexedDB data at the end of the session. This is useful to separately record an authentication step and reuse it later when recording more tests.
playwright codegen github.com/microsoft/playwright --save-storage=auth.json

登录
¥Login
执行身份验证并关闭浏览器后,auth.json
将包含存储状态,你可以在测试中重用该状态。
¥After performing authentication and closing the browser, auth.json
will contain the storage state which you can then reuse in your tests.

确保你仅在本地使用 auth.json
,因为它包含敏感信息。将其添加到你的 .gitignore
中,或者在完成生成测试后将其删除。
¥Make sure you only use the auth.json
locally as it contains sensitive information. Add it to your .gitignore
or delete it once you have finished generating your tests.
加载已验证状态
¥Load authenticated state
使用 --load-storage
运行以消耗之前从 auth.json
加载的存储空间。这样,所有 cookies、localStorage 和 IndexedDB 数据都将被恢复,使大多数 Web 应用进入经过身份验证的状态,而无需再次登录。这意味着你可以继续从登录状态生成测试。
¥Run with --load-storage
to consume the previously loaded storage from the auth.json
. This way, all cookies, localStorage and IndexedDB data will be restored, bringing most web apps to the authenticated state without the need to login again. This means you can continue generating tests from the logged in state.
playwright codegen --load-storage=auth.json github.com/microsoft/playwright

使用自定义设置进行录制
¥Record using custom setup
如果你想在某些非标准设置中使用 codegen(例如,使用 browser_context.route()),可以调用 page.pause(),它将打开一个带有 codegen 控件的单独窗口。
¥If you would like to use codegen in some non-standard setup (for example, use browser_context.route()), it is possible to call page.pause() that will open a separate window with codegen controls.
- Sync
- Async
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
# Make sure to run headed.
browser = p.chromium.launch(headless=False)
# Setup context however you like.
context = browser.new_context() # Pass any options
context.route('**/*', lambda route: route.continue_())
# Pause the page, and start recording manually.
page = context.new_page()
page.pause()
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
# Make sure to run headed.
browser = await p.chromium.launch(headless=False)
# Setup context however you like.
context = await browser.new_context() # Pass any options
await context.route('**/*', lambda route: route.continue_())
# Pause the page, and start recording manually.
page = await context.new_page()
await page.pause()
asyncio.run(main())