编写测试
介绍
🌐 Introduction
Playwright 测试很简单:它们执行操作并根据预期断言状态。
🌐 Playwright tests are simple: they perform actions and assert the state against expectations.
Playwright 会在执行每个操作之前自动等待 actionability 检查通过。你不需要添加手动等待或处理竞争条件。Playwright 断言旨在描述最终会满足的期望,从而消除不稳定的超时和竞争检查。
🌐 Playwright automatically waits for actionability checks to pass before performing each action. You don't need to add manual waits or deal with race conditions. Playwright assertions are designed to describe expectations that will eventually be met, eliminating flaky timeouts and racy checks.
你将学习
第一次测试
🌐 First test
看一下下面的示例,了解如何编写测试。
🌐 Take a look at the following example to see how to write a test.
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.nodejs.cn/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.nodejs.cn/');
// 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();
});
在 VS Code 中使用 JavaScript 时,在每个测试文件的开头添加 // @ts-check 以获得自动类型检查。
行动
🌐 Actions
导航
🌐 Navigation
大多数测试都是先导航到一个网址。之后,测试会与页面上的元素进行交互。
🌐 Most tests start by navigating to a URL. After that, the test interacts with page elements.
await page.goto('https://playwright.nodejs.cn/');
Playwright 会在页面达到加载状态后再继续。了解有关 page.goto() 的更多选项。
🌐 Playwright waits for the page to reach the load state before continuing. Learn more about page.goto() options.
交互
🌐 Interactions
执行操作首先需要定位元素。Playwright 使用 Locators API 来实现这一点。定位器代表了一种在页面上的任意时刻查找元素的方法。了解有关可用 不同类型 定位器的更多信息。
🌐 Performing actions starts with locating 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 会等待元素变为可操作状态后再执行操作,因此你无需等待它变得可用。
🌐 Playwright waits for the element to be actionable before performing the action, so you don't need to wait for it to become available.
// 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
这里是最受欢迎的 Playwright 操作。完整列表请查看 Locator API 部分。
🌐 Here are the most popular Playwright actions. For the complete list, check the Locator API section.
| 操作 | 描述 |
|---|---|
| locator.check() | 勾选输入框 |
| locator.click() | 点击元素 |
| locator.uncheck() | 取消勾选输入框 |
| locator.hover() | 鼠标悬停在元素上 |
| locator.fill() | 填写表单字段,输入文本 |
| locator.focus() | 聚焦元素 |
| locator.press() | 按下单个按键 |
| locator.setInputFiles() | 选择要上传的文件 |
| locator.selectOption() | 在下拉菜单中选择选项 |
断言
🌐 Assertions
Playwright 包含以 expect 函数形式的 测试断言。要进行断言,请调用 expect(value) 并选择一个符合预期的匹配器。
🌐 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 包含异步匹配器,它会等待直到满足预期条件。使用这些匹配器可以让测试不易出错且具有弹性。例如,这段代码会等待页面的标题包含“Playwright”:
🌐 Playwright includes async matchers that wait until the expected condition is met. Using these matchers makes tests non-flaky and resilient. For example, this code waits until the page gets the title containing "Playwright":
await expect(page).toHaveTitle(/Playwright/);
以下是最常用的异步断言。完整列表,请参见 断言指南:
🌐 Here are the most popular async assertions. For the complete list, see assertions guide:
Playwright 还包括通用匹配器,如 toEqual、toContain、toBeTruthy,可以用于断言任何条件。这些断言不使用 await 关键字,因为它们对已经可用的值执行即时同步检查。
🌐 Playwright also includes generic matchers like toEqual, toContain, toBeTruthy that can be used to assert any conditions. These assertions do not use the await keyword as they perform immediate synchronous checks on already available values.
expect(success).toBeTruthy();
测试隔离
🌐 Test Isolation
Playwright 测试基于test fixtures的概念,例如内置页面 fixture,它会传入到你的测试中。由于浏览器上下文(Browser Context)的存在,页面在测试之间是隔离的,这相当于一个全新的浏览器配置文件。每个测试都会获得一个全新的环境,即使多个测试在同一个浏览器中运行也是如此。
🌐 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. Every test gets a fresh environment, even when multiple tests run in a single browser.
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
你可以使用各种 测试钩子,例如 test.describe 来声明一组测试,以及在每个测试之前/之后执行的 test.beforeEach 和 test.afterEach。其他钩子包括 test.beforeAll 和 test.afterAll,它们在每个工作进程在所有测试之前/之后各执行一次。
🌐 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.
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.nodejs.cn/');
});
test('main navigation', async ({ page }) => {
// Assertions use the expect API.
await expect(page).toHaveURL('https://playwright.nodejs.cn/');
});
});
下一步是什么
🌐 What's Next