编写测试
介绍
¥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.
你将学习
¥You will learn
第一次测试
¥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
以获得自动类型检查。
¥Add // @ts-check
at the start of each test file when using JavaScript in VS Code to get automatic type checking.
行动
¥Actions
导航
¥Navigation
大多数测试都是从导航到 URL 开始的。之后,测试将与页面元素进行交互。
¥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 为此使用 定位器 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 会等待元素变为 actionable 后再执行操作,因此你无需等待它变为可用状态。
¥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 操作。完整列表,请查看 定位器 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 测试基于 测试治具 的概念,例如 内置页面夹具,它会传递到你的测试中。页面是 由于浏览器上下文而在测试之间隔离,相当于一个全新的浏览器配置文件。每个测试都会获得一个全新的环境,即使在单个浏览器中运行多个测试也是如此。
¥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