Skip to main content

测试生成器

介绍

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.

在 VS Code 中生成测试

Generate tests in VS Code

安装 VS Code 扩展并直接从 VS Code 生成测试。该扩展在 VS Code 市场 上可用。查看我们的 VS Code 入门 指南。

Install the VS Code extension and generate tests directly from VS Code. The extension is available on the VS Code Marketplace. Check out our guide on getting started with VS Code.

记录新测试

Record a New Test

要录制测试,请单击测试侧栏中的录制新按钮。这将创建一个 test-1.spec.ts 文件并打开一个浏览器窗口。

To record a test click on the Record new button from the Testing sidebar. This will create a test-1.spec.ts file as well as open up a browser window.

record new in vs code

在浏览器中,转到你要测试的 URL,然后开始单击以记录你的用户操作。

In the browser go to the URL you wish to test and start clicking around to record your user actions.

generating user actions

Playwright 将记录你的操作并直接在 VS Code 中生成测试代码。你还可以通过选择工具栏中的图标之一,然后单击页面上要断言的元素来生成断言。可以生成以下断言:

Playwright will record your actions and generate the test code directly in VS Code. You can also generate assertions by choosing one of the icons in the toolbar and then clicking on an element on the page to assert against. The following assertions can be generated:

  • '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

generating assertions

完成录制后,单击取消按钮或关闭浏览器窗口。然后,你可以检查 test-1.spec.ts 文件并根据需要手动改进它。

Once you are done recording click the cancel button or close the browser window. You can then inspect your test-1.spec.ts file and manually improve it if needed.

code from a generated test

在光标处记录

Record at Cursor

要从测试中的特定点开始录制,请将光标移动到要录制更多操作的位置,然后单击“测试”侧栏中的“在光标处录制”按钮。如果你的浏览器窗口尚未打开,请首先在选中 '显示浏览器' 的情况下运行测试,然后单击“在光标处记录”按钮。

To record from a specific point in your test move your cursor to where you want to record more actions and then click the Record at cursor button from the Testing sidebar. If your browser window is not already open then first run the test with 'Show browser' checked and then click the Record at cursor button.

record at cursor in vs code

在浏览器窗口中开始执行你要记录的操作。

In the browser window start performing the actions you want to record.

add feed the dog to todo app

在 VS Code 的测试文件中,你将看到新生成的操作已添加到测试中的光标位置。

In the test file in VS Code you will see your new generated actions added to your test at the cursor position.

code from a generated test

生成定位器

Generating locators

你可以使用测试生成器生成定位器。

You can generate locators with the test generator.

  • 单击测试侧边栏中的“选择定位器”按钮,然后将鼠标悬停在浏览器窗口中的元素上,以查看每个元素下方高亮的 locator

    Click on the Pick locator button form the testing sidebar and then hover over elements in the browser window to see the locator highlighted underneath each element.

  • 单击所需的元素,它现在将显示在 VS Code 的“选择定位器”框中。

    Click the element you require and it will now show up in the Pick locator box in VS Code.

  • 按键盘上的 Enter 将定位器复制到剪贴板中,然后粘贴到代码中的任意位置。或者如果你想取消,请按 'escape'。

    Press Enter on your keyboard to copy the locator into the clipboard and then paste anywhere in your code. Or press 'escape' if you want to cancel.

Pick locators in VS code

使用 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.

npx 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

Recording a test

完成与页面的交互后,按录制按钮停止录制,并使用复制按钮将生成的代码复制到编辑器。

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.

要了解有关生成测试的更多信息,请查看 代码生成器 上的详细指南。

To learn more about generating tests check out or detailed guide on Codegen.

生成定位器

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.

picking a locator

模拟

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.

npx playwright codegen --viewport-size=800,600 playwright.dev
Codegen generating code for tests for playwright.dev website with a specific viewport js

模拟设备

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.

npx playwright codegen --device="iPhone 13" playwright.dev
Codegen generating code for tests for playwright.dev website emulated for iPhone 13 js

模拟配色方案

Emulate color scheme

记录脚本和测试,同时使用 --color-scheme 选项模拟配色方案。

Record scripts and tests while emulating the color scheme with the --color-scheme option.

npx playwright codegen --color-scheme=dark playwright.dev
Codegen generating code for tests for playwright.dev website in dark mode js

模拟地理位置、语言和时区

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:

  1. 接受 cookies

    Accept the cookies

  2. 单击右上角的“定位我”按钮即可查看实际的地理定位。

    On the top right click on the locate me button to see geolocation in action.

npx playwright codegen --timezone="Europe/Rome" --geolocation="41.890221,12.492348" --lang="it-IT" bing.com/maps
Codegen generating code for tests for bing maps showing timezone, geolocation as Rome, Italy and in Italian language

保留经过身份验证的状态

Preserve authenticated state

运行 codegen--save-storage 以在会话结束时保存 cookieslocalStorage。这对于单独记录身份验证步骤并在稍后记录更多测试时重复使用非常有用。

Run codegen with --save-storage to save cookies and localStorage at the end of the session. This is useful to separately record an authentication step and reuse it later when recording more tests.

npx playwright codegen github.com/microsoft/playwright --save-storage=auth.json
github page before logging in js

登录

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.

login to Github screen

确保你仅在本地使用 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 加载的存储空间。这样,所有 cookieslocalStorage 都将被恢复,使大多数 Web 应用进入经过身份验证的状态,而无需再次登录。这意味着你可以继续从登录状态生成测试。

Run with --load-storage to consume the previously loaded storage from the auth.json. This way, all cookies and localStorage will be restored, bringing most web apps to the authenticated state without the need to login again. This means you can can continue generating tests from the logged in state.

npx playwright codegen --load-storage=auth.json github.com/microsoft/playwright
github signed in showing use of load storage js

使用自定义设置进行录制

Record using custom setup

如果你想在某些非标准设置中使用 codegen(例如,使用 browserContext.route()),可以调用 page.pause(),它将打开一个带有 codegen 控件的单独窗口。

If you would like to use codegen in some non-standard setup (for example, use browserContext.route()), it is possible to call page.pause() that will open a separate window with codegen controls.

const { chromium } = require('@playwright/test');

(async () => {
// Make sure to run headed.
const browser = await chromium.launch({ headless: false });

// Setup context however you like.
const context = await browser.newContext({ /* pass any options */ });
await context.route('**/*', route => route.continue());

// Pause the page, and start recording manually.
const page = await context.newPage();
await page.pause();
})();