Playwright E2E 测试生成(页面对象模式)

发布于 2026/8/4作者:TokenLens发私信来源:self

为关键用户流程生成 Playwright E2E 测试,采用 Page Object Model,含 CI 配置、截图对比、重试策略

提示词

你是 QA 自动化专家。任务:为给定的用户场景生成 Playwright E2E 测试。

约束:

  1. 采用 Page Object Model:每页一个 .ts 文件,封装定位器与操作
  2. 测试用例独立、可并行、可重复运行(beforeEach 清理状态)
  3. 关键断言:可见性、文本、URL、网络请求、截图对比
  4. 使用 data-testid 定位,避免 CSS 选择器脆弱
  5. 配置:retries=2, timeout=30s, trace=on-first-retry
  6. CI 片段:GitHub Actions 矩阵(chromium/firefox/webkit),上传 trace/截图
  7. 输出:Page Objects + 测试套件 + playwright.config.ts 片段 + CI yaml

输出格式:

// pages/LoginPage.ts
// tests/login.spec.ts
.github/workflows/e2e.yml 片段:

少样本示例

展示 POM、data-testid、trace、截图、重试配置

输入

// 场景:用户登录 -> 进入仪表盘 -> 创建项目 -> 验证列表
// 页面结构:/login, /dashboard, /projects/new

输出

// pages/LoginPage.ts
export class LoginPage {
readonly page: Page;
readonly email = this.page.getByTestId('email-input');
readonly password = this.page.getByTestId('password-input');
readonly submit = this.page.getByTestId('login-submit');
constructor(page: Page) { this.page = page; }
async goto() { await this.page.goto('/login'); }
async login(email: string, password: string) {
await this.email.fill(email);
await this.password.fill(password);
await this.submit.click();
await this.page.waitForURL('/dashboard');
}
}

// tests/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';

test.describe('Login Flow', () => {
test('successful login redirects to dashboard', async ({ page }) => {
const login = new LoginPage(page);
await login.goto();
await login.login('user@example.com', 'secret123');
await expect(page.getByTestId('dashboard-title')).toBeVisible();
});
});

// playwright.config.ts 片段
export default defineConfig({
retries: 2,
timeout: 30000,
use: { trace: 'on-first-retry', screenshot: 'only-on-failure' },
});

改写到我的

评分

暂无评分

登录后可为这条 Prompt 打分

评价与讨论

直接在本页发言

加载讨论…

登录后即可在本页参与讨论

测试生成编程与工程typescriptplaywrighte2epage-objectci