端到端测试
规则
- 使用 Playwright 进行端到端测试——跨浏览器、自动等待、内置测试运行器、优秀的 CI 支持
- 定位器优先级:
getByRole() > getByLabel() > getByPlaceholder() > getByTestId() > CSS 选择器
- 页面对象模型:将页面交互封装在类中——
LoginPage.login(email, password)
- 测试隔离:每个测试以全新状态开始——使用
beforeEach 进行设置,避免测试间依赖
- 自动等待:Playwright 自动等待元素——不要添加手动
waitForTimeout() 调用
- 断言:使用
expect(locator) web 优先断言——toBeVisible()、toHaveText()、toHaveURL()
- 并行执行:默认并行运行测试——确保测试之间没有共享的可变状态
- CI:在无头模式下运行,配置重试次数(CI 中设置
retries: 2),失败时上传追踪
- 视觉回归:
expect(page).toHaveScreenshot()——使用 --update-snapshots 更新基线
模式
class LoginPage {
constructor(private page: Page) {}
async goto() { await this.page.goto("/login"); }
async login(email: string, password: string) {
await this.page.getByLabel("邮箱").fill(email);
await this.page.getByLabel("密码").fill(password);
await this.page.getByRole("button", { name: "登录" }).click();
await this.page.waitForURL("/dashboard");
}
}
export default defineConfig({
retries: process.env.CI ? 2 : 0,
use: { trace: "on-first-retry", screenshot: "only-on-failure" },
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "mobile", use: { ...devices["Pixel 5"] } },
],
});
避免
page.waitForTimeout() —— 使用自动等待或 waitForURL()、waitForResponse()
- 为交互元素使用 CSS 选择器 —— 使用基于角色的定位器以获得弹性
- 依赖于其他测试状态的测试 —— 每个测试必须独立可运行
- 直接测试第三方服务 —— 使用
page.route() 模拟外部 API
- 跳过移动端视口 —— 在你的项目矩阵中至少测试一个移动设备