这是用户在 2024-12-25 17:35 为 https://playwright.dev/docs/writing-tests 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
Skip to main content
跳过主要内容

Writing tests

Introduction  简介

Playwright tests are simple, they
Playwright 测试简单,它们

  • perform actions, and  执行操作,和
  • assert the state against expectations.
    断言状态与预期相符。

There is no need to wait for anything prior to performing an action: Playwright automatically waits for the wide range of actionability checks to pass prior to performing each action.
无需在执行操作之前等待任何事物:Playwright 会自动等待广泛的可用性检查通过后再执行每个操作。

There is also no need to deal with the race conditions when performing the checks - Playwright assertions are designed in a way that they describe the expectations that need to be eventually met.
无需在执行检查时处理竞态条件 - Playwright 断言的设计方式是描述最终需要满足的期望。

That's it! These design choices allow Playwright users to forget about flaky timeouts and racy checks in their tests altogether.
那是!这些设计选择让 Playwright 用户在测试中完全忘记易变的超时和竞态检查。

You will learn  您将学习

First test  第一次测试

Take a look at the following example to see how to write a test.
查看以下示例以了解如何编写测试。

tests/example.spec.ts  tests/example.spec.ts 测试/example.spec.ts
import { test, expect } from '@playwright/test';

test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');

// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});

test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');

// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();

// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});
note  注意

Add // @ts-check at the start of each test file when using JavaScript in VS Code to get automatic type checking.
在 VS Code 中使用 JavaScript 时,在每个测试文件的开头添加 // @ts-check 以获得自动类型检查。

Actions  动作

Most of the tests will start with navigating page to the URL. After that, test will be able to interact with the page elements.
大多数测试将从导航到页面 URL 开始。之后,测试将能够与页面元素进行交互。

await page.goto('https://playwright.dev/');

Playwright will wait for page to reach the load state prior to moving forward. Learn more about the page.goto() options.
Playwright 将在页面达到加载状态之前等待,然后继续前进。了解关于 page.goto()选项的更多信息。

Interactions  交互

Performing actions starts with locating the elements. Playwright uses Locators API for that. Locators represent a way to find element(s) on the page at any moment, learn more about the different types of locators available. Playwright will wait for the element to be actionable prior to performing the action, so there is no need to wait for it to become available.
执行操作从定位元素开始。Playwright 使用定位器 API 来完成这个任务。定位器代表了一种在任何时刻在页面上查找元素(们)的方式,了解更多关于可用的不同类型定位器的信息。在执行操作之前,Playwright 将等待元素变为可操作状态,因此无需等待其变为可用。

// Create a locator.
const getStarted = page.getByRole('link', { name: 'Get started' });

// Click it.
await getStarted.click();

In most cases, it'll be written in one line:
在大多数情况下,它将写在一行中:

await page.getByRole('link', { name: 'Get started' }).click();

Basic actions  基本操作

This is the list of the most popular Playwright actions. Note that there are many more, so make sure to check the Locator API section to learn more about them.
这是最受欢迎的 Playwright 动作的列表。请注意,还有很多其他的,请确保查看定位器 API 部分,以了解更多信息。

Action  操作Description  描述
locator.check()  定位器.检查()Check the input checkbox  检查输入复选框
locator.click()  定位器.点击()Click the element  点击元素
locator.uncheck()Uncheck the input checkbox
取消选中输入复选框
locator.hover()Hover mouse over the element
鼠标悬停在元素上
locator.fill()  定位器.填充()Fill the form field, input text
填写表单字段,输入文本
locator.focus()Focus the element  聚焦元素
locator.press()  定位器.按()Press single key  按单个键
locator.setInputFiles()  setter.setInputFiles()Pick files to upload  选择文件上传
locator.selectOption()  选择选项()Select option in the drop down
选择下拉菜单中的选项

Assertions  断言

Playwright includes test assertions in the form of expect function. To make an assertion, call expect(value) and choose a matcher that reflects the expectation.
Playwright 包含以 expect 函数形式的测试断言。要执行断言,请调用 expect(value) 并选择一个反映期望的匹配器。

There are many generic matchers like toEqual, toContain, toBeTruthy that can be used to assert any conditions.
有许多通用的匹配器,如 toEqualtoContaintoBeTruthy ,可以用来断言任何条件。

expect(success).toBeTruthy();

Playwright also includes async matchers that will wait until the expected condition is met. Using these matchers allows making the tests non-flaky and resilient. For example, this code will wait until the page gets the title containing "Playwright":
Playwright 还包括异步匹配器,它将等待直到满足预期条件。使用这些匹配器可以使测试变得非易失性和健壮。例如,此代码将等待直到页面获取包含 "Playwright" 的标题:

await expect(page).toHaveTitle(/Playwright/);

Here is the list of the most popular async assertions. Note that there are many more to get familiar with:
以下是最受欢迎的异步断言列表。请注意,还有更多需要熟悉的内容:

Assertion  断言Description  描述
expect(locator).toBeChecked()
期望(locator).toBeChecked()
Checkbox is checked  复选框被选中
expect(locator).toBeEnabled()
期望(locator).toBeEnabled()
Control is enabled  控制已启用
expect(locator).toBeVisible()
期望(locator).toBe 可见()
Element is visible  元素可见
expect(locator).toContainText()
期望(locator).包含文本()
Element contains text  元素包含文本
expect(locator).toHaveAttribute()
期待(locator).应有属性()
Element has attribute  元素有属性
expect(locator).toHaveCount()
期望(locator).应有数量()
List of elements has given length
元素列表已给出长度
expect(locator).toHaveText()
期望(locator).应有文本()
Element matches text  元素匹配文本
expect(locator).toHaveValue()
期望(locator).应有值()
Input element has value  输入元素有值
expect(page).toHaveTitle()
期望(page).要有标题()
Page has title  页面有标题
expect(page).toHaveURL()
期望(page).toHaveURL()
Page has URL  页面有 URL

Test Isolation  测试隔离

Playwright Test is based on the concept of test fixtures such as the built in page fixture, which is passed into your test. Pages are isolated between tests due to the Browser Context, which is equivalent to a brand new browser profile, where every test gets a fresh environment, even when multiple tests run in a single Browser.
Playwright 测试基于测试固件的概念,例如内置的页面固件,该固件传递到您的测试中。由于浏览器上下文,页面在测试之间是隔离的,这相当于一个新的浏览器配置文件,即使多个测试在单个浏览器中运行,每个测试也能获得一个全新的环境。

tests/example.spec.ts  tests/example.spec.ts 测试/example.spec.ts
import { test } from '@playwright/test';

test('example test', async ({ page }) => {
// "page" belongs to an isolated BrowserContext, created for this specific test.
});

test('another test', async ({ page }) => {
// "page" in this second test is completely isolated from the first test.
});

Using Test Hooks  使用测试钩子

You can use various test hooks such as test.describe to declare a group of tests and test.beforeEach and test.afterEach which are executed before/after each test. Other hooks include the test.beforeAll and test.afterAll which are executed once per worker before/after all tests.
您可以使用各种测试钩子,如 test.describe 来声明一组测试,以及 test.beforeEachtest.afterEach ,它们在每个测试前后执行。其他钩子包括 test.beforeAlltest.afterAll ,它们在每个工作进程开始/结束时执行一次所有测试。

tests/example.spec.ts  tests/example.spec.ts 测试/example.spec.ts
import { test, expect } from '@playwright/test';

test.describe('navigation', () => {
test.beforeEach(async ({ page }) => {
// Go to the starting url before each test.
await page.goto('https://playwright.dev/');
});

test('main navigation', async ({ page }) => {
// Assertions use the expect API.
await expect(page).toHaveURL('https://playwright.dev/');
});
});

What's Next  下一步是什么