Skip to content

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 的老大难)。

五、快速生成测试:codegen

不想手写选择器?用录制:

bash
npx playwright codegen https://example.com

会打开浏览器,你手动操作一遍,它自动生成测试代码——比自己猜选择器准得多。

小结

  • Playwright 做端到端测试:模拟用户操作整个页面链路
  • 核心:gotofill/clickexpect 断言
  • 自动等待省心,codegen 录制省事
  • 适合:登录、下单、搜索等关键链路回归

想了解 UI 测试怎么接入 CI(GitHub Actions 跑 Playwright),看「CI/CD 快速入门」(文章整理中)。