Playwright 是微软开源的端到端(E2E)测试工具——用代码模拟用户操作浏览器(点击、输入、跳转),验证整个页面链路。相比 Selenium 更现代(自带等待、自动录制)。这篇快速入门:装起来、跑起来、写断言。
一、解决什么问题:整个页面的“真实”测试
单元测试测的是单个方法;UI 测试测的是用户真实操作页面——打开页面、填表单、点按钮、看结果。它验证“页面链路”(登录→下单→支付),单测覆盖不到的集成问题靠它。
二、安装
bash
npm init -y
npm install -D @playwright/test
npx playwright install chromium # 下载浏览器三、第一个测试
tests/example.spec.js:
js
const { test, expect } = require('@playwright/test')
test('搜索功能', async ({ page }) => {
await page.goto('https://example.com') // 打开页面
await page.fill('#search', '设计模式') // 填输入框
await page.click('.search-btn') // 点按钮
await expect(page).toHaveTitle(/搜索结果/) // 断言标题
await expect(page.locator('.result-item').first()).toBeVisible() // 断言元素可见
})运行:
bash
npx playwright test # 无头模式跑
npx playwright test --headed # 带浏览器看
npx playwright show-report # 查看 HTML 报告四、核心 API
| API | 作用 |
|---|---|
page.goto(url) | 跳转页面 |
page.fill(选择器, 值) | 填输入框 |
page.click(选择器) | 点击 |
page.locator(选择器) | 定位元素 |
expect(...).toBeVisible() | 断言元素可见 |
expect(page).toHaveURL(...) | 断言当前 URL |
Playwright 的杀手锏:自动等待——click/expect 会自动等元素出现,不用手动 sleep(Selenium 的老大难)。
选择器除了 CSS(#search、.search-btn),还有语义化定位:getByRole('button', { name: '搜索' })、getByPlaceholder('请输入关键词')——贴近用户视角,不怕前端改样式。进阶用法见《E2E Playwright 实战》。
五、快速生成测试:codegen
不想手写选择器?用录制:
bash
npx playwright codegen https://example.com会打开浏览器,你手动操作一遍,它自动生成测试代码——比自己猜选择器准得多。
小结
- Playwright 做端到端测试:模拟用户操作整个页面链路
- 核心:
goto→fill/click→expect断言 - 自动等待省心,
codegen录制省事 - 适合:登录、下单、搜索等关键链路回归
验证说明:本文示例代码用 Playwright 本地实跑验证(本地 demo 页 + Chrome headless,
toHaveTitle/toBeVisible/toHaveURL断言全 PASS)。
接下来可以看:
- 动手进阶(登录 mock、网络拦截、真实项目链路):《E2E Playwright 实战》
- Web 端思路搬到移动端怎么用:《Android UI 测试快速入门》
- 测试过了怎么接入流水线(GitHub Actions 跑 Playwright):《CI/CD 快速入门》
