[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MG1ENHKZ2JBV2X0VJ0AH10":3,"skill-same:01M6MG1ENHKZ2JBV2X0VJ0AH10":50},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":21,"linkOnly":22,"markdownContent":23,"markdownBody":24,"frontMatter":25,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":31,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M6MG1ENHKZ2JBV2X0VJ0AH10","e2e-playwright",null,"hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1575,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fe2e-playwright\u002FSKILL.md",[],[18,19,20],"playwright","e2e","e2e playwright","2026-11-10 10:12:30",false,"---\n\nname: qa\u002Fe2e-playwright\ndescription: Playwright E2E 测试完整方法论，涵盖项目初始化、Page Object Model、认证复用、API Mock、视觉回归、多浏览器测试、CI 集成和调试技巧\nversion: 1.0.0\nagent: qa\ntype: methodology\nuser-invocable: false\nagent-invocable: true\ndependencies:\n- shared\u002Ftech-stack-detection\n  triggers:\n- 需要编写或执行 E2E 测试时\n- 需要配置 Playwright 测试环境时\n- 门禁要求 E2E 测试通过时\n- 需要视觉回归测试时\n  metadata:\n  internal: true\n\n---\n\n# Playwright E2E 测试方法论\n\n## 适用场景\n\n- Web 项目需要编写端到端测试\n- 门禁（Gate 1）要求 E2E 测试通过\n- 需要覆盖关键用户流程的自动化验证\n- 需要多浏览器\u002F多视口兼容性验证\n- 需要视觉回归测试\n\n---\n\n## 1. 项目初始化\n\n### 1.1 安装\n\n```bash\n# 新项目初始化（推荐）\nnpm init playwright@latest\n\n# 已有项目添加\nnpm install -D @playwright\u002Ftest\nnpx playwright install\n```\n\n### 1.2 配置文件（`playwright.config.ts`）\n\n```typescript\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Fe2e',\n  \u002F\u002F 测试产物目录\n  outputDir: '.\u002Fe2e\u002Ftest-results',\n\n  \u002F\u002F 全局超时\n  timeout: 30_000,\n  expect: { timeout: 5_000 },\n\n  \u002F\u002F 并行执行\n  fullyParallel: true,\n  workers: process.env.CI ? 1 : undefined,\n\n  \u002F\u002F 失败重试（CI 中重试一次减少 flaky）\n  retries: process.env.CI ? 1 : 0,\n\n  \u002F\u002F 报告\n  reporter: [\n    ['html', { outputFolder: '.\u002Fe2e\u002Fplaywright-report' }],\n    ['json', { outputFile: '.\u002Fe2e\u002Ftest-results\u002Fresults.json' }],\n    \u002F\u002F CI 中额外输出到 stdout\n    ...(process.env.CI ? [['github'] as const] : []),\n  ],\n\n  \u002F\u002F 全局配置\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    \u002F\u002F 失败时自动截图\n    screenshot: 'only-on-failure',\n    \u002F\u002F 失败时录制 trace\n    trace: 'on-first-retry',\n    \u002F\u002F 失败时录制视频\n    video: 'on-first-retry',\n  },\n\n  \u002F\u002F 多浏览器 + 移动端视口\n  projects: [\n    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },\n    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },\n    { name: 'webkit', use: { ...devices['Desktop Safari'] } },\n    { name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },\n    { name: 'mobile-safari', use: { ...devices['iPhone 13'] } },\n  ],\n\n  \u002F\u002F 开发服务器自动启动\n  webServer: {\n    command: 'npm run dev',\n    url: 'http:\u002F\u002Flocalhost:3000',\n    reuseExistingServer: !process.env.CI,\n    timeout: 120_000,\n  },\n});\n```\n\n**关键配置说明**：\n\n| 配置项          | 作用                   | 建议值            |\n| --------------- | ---------------------- | ----------------- |\n| `fullyParallel` | 测试文件间并行执行     | `true`            |\n| `workers`       | 并行 worker 数         | CI 为 1，本地默认 |\n| `retries`       | 失败重试次数           | CI 为 1，本地为 0 |\n| `trace`         | 失败时生成可视化时间线 | `on-first-retry`  |\n| `webServer`     | 自动启动开发服务器     | 必须配置          |\n\n### 1.3 目录结构\n\n```\ne2e\u002F\n├── playwright.config.ts        # 配置文件（或放在项目根目录）\n├── fixtures\u002F                   # 自定义 fixtures\n│   ├── base.ts                 # 扩展 base test\n│   └── auth.ts                 # 认证 fixture\n├── pages\u002F                      # Page Object Models\n│   ├── login.page.ts\n│   ├── dashboard.page.ts\n│   └── components\u002F             # 可复用组件 POM\n│       ├── navbar.component.ts\n│       └── modal.component.ts\n├── specs\u002F                      # 测试用例\n│   ├── auth\u002F\n│   │   ├── login.spec.ts\n│   │   └── register.spec.ts\n│   ├── dashboard\u002F\n│   │   └── dashboard.spec.ts\n│   └── crud\u002F\n│       └── user-management.spec.ts\n├── helpers\u002F                    # 测试工具\n│   ├── seed.ts                 # 数据种子\n│   └── cleanup.ts              # 数据清理\n├── test-results\u002F               # 测试产物（gitignore）\n└── playwright-report\u002F          # HTML 报告（gitignore）\n```\n\n---\n\n## 2. Page Object Model（POM）\n\n### 2.1 核心原则\n\n- **每个页面一个 POM 类**：封装定位器和操作方法\n- **不暴露 Locator**：外部只调用语义化方法\n- **组件级复用**：导航栏、弹窗等提取为独立组件 POM\n\n### 2.2 基础 POM\n\n```typescript\n\u002F\u002F e2e\u002Fpages\u002Flogin.page.ts\nimport { type Page, type Locator } from '@playwright\u002Ftest';\n\nexport class LoginPage {\n  private readonly emailInput: Locator;\n  private readonly passwordInput: Locator;\n  private readonly submitButton: Locator;\n  private readonly errorMessage: Locator;\n\n  constructor(private readonly page: Page) {\n    this.emailInput = page.getByLabel('邮箱');\n    this.passwordInput = page.getByLabel('密码');\n    this.submitButton = page.getByRole('button', { name: '登录' });\n    this.errorMessage = page.getByRole('alert');\n  }\n\n  async goto() {\n    await this.page.goto('\u002Flogin');\n  }\n\n  async login(email: string, password: string) {\n    await this.emailInput.fill(email);\n    await this.passwordInput.fill(password);\n    await this.submitButton.click();\n  }\n\n  async getErrorMessage() {\n    return this.errorMessage.textContent();\n  }\n}\n```\n\n### 2.3 组件 POM\n\n```typescript\n\u002F\u002F e2e\u002Fpages\u002Fcomponents\u002Fnavbar.component.ts\nimport { type Page, type Locator } from '@playwright\u002Ftest';\n\nexport class NavbarComponent {\n  private readonly userMenu: Locator;\n  private readonly logoutButton: Locator;\n\n  constructor(private readonly page: Page) {\n    this.userMenu = page.getByTestId('user-menu');\n    this.logoutButton = page.getByRole('menuitem', { name: '退出登录' });\n  }\n\n  async logout() {\n    await this.userMenu.click();\n    await this.logoutButton.click();\n  }\n\n  async getUserDisplayName() {\n    return this.userMenu.textContent();\n  }\n}\n```\n\n### 2.4 定位器优先级\n\n选择定位器时遵循以下优先级（可靠性从高到低）：\n\n| 优先级 | 方法               | 示例                                    | 说明               |\n| ------ | ------------------ | --------------------------------------- | ------------------ |\n| 1      | `getByRole`        | `getByRole('button', { name: '提交' })` | 无障碍语义，最稳定 |\n| 2      | `getByLabel`       | `getByLabel('邮箱')`                    | 表单元素首选       |\n| 3      | `getByPlaceholder` | `getByPlaceholder('请输入邮箱')`        | 备选               |\n| 4      | `getByText`        | `getByText('欢迎回来')`                 | 静态文本           |\n| 5      | `getByTestId`      | `getByTestId('submit-btn')`             | 无语义标记时的兜底 |\n| 6      | CSS\u002FXPath          | `page.locator('.btn-primary')`          | **尽量避免**       |\n\n---\n\n## 3. 认证状态复用\n\n### 3.1 Global Setup 方式\n\n```typescript\n\u002F\u002F e2e\u002Fglobal-setup.ts\nimport { chromium, type FullConfig } from '@playwright\u002Ftest';\n\nasync function globalSetup(config: FullConfig) {\n  const browser = await chromium.launch();\n  const page = await browser.newPage();\n\n  \u002F\u002F 执行登录\n  await page.goto('http:\u002F\u002Flocalhost:3000\u002Flogin');\n  await page.getByLabel('邮箱').fill('admin@example.com');\n  await page.getByLabel('密码').fill('password');\n  await page.getByRole('button', { name: '登录' }).click();\n  await page.waitForURL('\u002Fdashboard');\n\n  \u002F\u002F 保存认证状态\n  await page.context().storageState({ path: '.\u002Fe2e\u002F.auth\u002Fadmin.json' });\n  await browser.close();\n}\n\nexport default globalSetup;\n```\n\n**配置引用**：\n\n```typescript\n\u002F\u002F playwright.config.ts\nexport default defineConfig({\n  globalSetup: '.\u002Fe2e\u002Fglobal-setup.ts',\n  projects: [\n    \u002F\u002F 不带认证的测试\n    { name: 'public', testMatch: \u002Fpublic\\.spec\\.ts\u002F },\n    \u002F\u002F 带认证的测试\n    {\n      name: 'authenticated',\n      use: { storageState: '.\u002Fe2e\u002F.auth\u002Fadmin.json' },\n      testIgnore: \u002Fpublic\\.spec\\.ts\u002F,\n    },\n  ],\n});\n```\n\n### 3.2 多角色认证\n\n```typescript\n\u002F\u002F e2e\u002Ffixtures\u002Fauth.ts\nimport { test as base } from '@playwright\u002Ftest';\n\ntype AuthFixtures = {\n  adminPage: Page;\n  userPage: Page;\n};\n\nexport const test = base.extend\u003CAuthFixtures>({\n  adminPage: async ({ browser }, use) => {\n    const context = await browser.newContext({\n      storageState: '.\u002Fe2e\u002F.auth\u002Fadmin.json',\n    });\n    const page = await context.newPage();\n    await use(page);\n    await context.close();\n  },\n  userPage: async ({ browser }, use) => {\n    const context = await browser.newContext({\n      storageState: '.\u002Fe2e\u002F.auth\u002Fuser.json',\n    });\n    const page = await context.newPage();\n    await use(page);\n    await context.close();\n  },\n});\n```\n\n---\n\n## 4. API Mocking\n\n### 4.1 使用 `page.route` 拦截请求\n\n```typescript\ntest('显示用户列表（API Mock）', async ({ page }) => {\n  \u002F\u002F 拦截 API 请求\n  await page.route('\u002Fapi\u002Fusers', async (route) => {\n    await route.fulfill({\n      status: 200,\n      contentType: 'application\u002Fjson',\n      body: JSON.stringify([\n        { id: 1, name: '张三', email: 'zhang@example.com' },\n        { id: 2, name: '李四', email: 'li@example.com' },\n      ]),\n    });\n  });\n\n  await page.goto('\u002Fusers');\n  await expect(page.getByText('张三')).toBeVisible();\n  await expect(page.getByText('李四')).toBeVisible();\n});\n```\n\n### 4.2 模拟错误响应\n\n```typescript\ntest('API 失败时显示错误提示', async ({ page }) => {\n  await page.route('\u002Fapi\u002Fusers', async (route) => {\n    await route.fulfill({ status: 500, body: 'Internal Server Error' });\n  });\n\n  await page.goto('\u002Fusers');\n  await expect(page.getByText('加载失败')).toBeVisible();\n  await expect(page.getByRole('button', { name: '重试' })).toBeVisible();\n});\n```\n\n### 4.3 Mock 与真实请求混合\n\n```typescript\ntest('部分 API Mock', async ({ page }) => {\n  \u002F\u002F 只 Mock 第三方支付接口，其余走真实请求\n  await page.route('**\u002Fapi\u002Fpayment\u002F**', async (route) => {\n    await route.fulfill({\n      status: 200,\n      body: JSON.stringify({ success: true, transactionId: 'mock-tx-001' }),\n    });\n  });\n\n  await page.goto('\u002Fcheckout');\n  \u002F\u002F ... 执行支付流程\n});\n```\n\n### 4.4 何时用 Mock vs 真实 API\n\n| 场景                     | 建议                             |\n| ------------------------ | -------------------------------- |\n| 核心用户路径             | **真实 API**（关键路径证据规则） |\n| 第三方服务（支付、邮件） | Mock                             |\n| 错误\u002F边界状态            | Mock                             |\n| 加载状态、空数据         | Mock                             |\n| 数据量大的列表\u002F分页      | Mock + 至少一条真实路径          |\n\n⚠️ **Boss 门禁规则**：核心用户路径只由 Mock 证明的，必须标记为**未验证**，不能作为发布证据。\n\n---\n\n## 5. 关键用户流程测试（必须覆盖）\n\n### 5.1 CRUD 完整流程\n\n```typescript\n\u002F\u002F e2e\u002Fspecs\u002Fcrud\u002Fuser-management.spec.ts\nimport { test, expect } from '@playwright\u002Ftest';\nimport { UserListPage } from '..\u002F..\u002Fpages\u002Fuser-list.page';\nimport { UserFormPage } from '..\u002F..\u002Fpages\u002Fuser-form.page';\n\ntest.describe('用户管理 CRUD', () => {\n  let userList: UserListPage;\n  let userForm: UserFormPage;\n\n  test.beforeEach(async ({ page }) => {\n    userList = new UserListPage(page);\n    userForm = new UserFormPage(page);\n    await userList.goto();\n  });\n\n  test('创建 → 编辑 → 删除完整流程', async ({ page }) => {\n    \u002F\u002F 创建\n    await userList.clickAddUser();\n    await userForm.fillName('测试用户');\n    await userForm.fillEmail('test@example.com');\n    await userForm.submit();\n    await expect(page.getByText('测试用户')).toBeVisible();\n\n    \u002F\u002F 编辑\n    await userList.editUser('测试用户');\n    await userForm.fillName('修改后的用户');\n    await userForm.submit();\n    await expect(page.getByText('修改后的用户')).toBeVisible();\n    await expect(page.getByText('测试用户')).not.toBeVisible();\n\n    \u002F\u002F 删除\n    await userList.deleteUser('修改后的用户');\n    await userList.confirmDelete();\n    await expect(page.getByText('修改后的用户')).not.toBeVisible();\n  });\n\n  test('列表分页展示', async ({ page }) => {\n    await expect(userList.getTable()).toBeVisible();\n    await userList.goToNextPage();\n    await expect(page).toHaveURL(\u002Fpage=2\u002F);\n  });\n\n  test('空列表提示', async ({ page }) => {\n    \u002F\u002F 使用 route mock 空数据场景\n    await page.route('\u002Fapi\u002Fusers*', (route) =>\n      route.fulfill({ status: 200, body: JSON.stringify({ data: [], total: 0 }) }),\n    );\n    await page.reload();\n    await expect(page.getByText('暂无数据')).toBeVisible();\n  });\n});\n```\n\n### 5.2 认证流程\n\n```typescript\n\u002F\u002F e2e\u002Fspecs\u002Fauth\u002Flogin.spec.ts\nimport { test, expect } from '@playwright\u002Ftest';\nimport { LoginPage } from '..\u002F..\u002Fpages\u002Flogin.page';\n\ntest.describe('登录', () => {\n  let loginPage: LoginPage;\n\n  test.beforeEach(async ({ page }) => {\n    loginPage = new LoginPage(page);\n    await loginPage.goto();\n  });\n\n  test('正确凭据成功登录', async ({ page }) => {\n    await loginPage.login('admin@example.com', 'password');\n    await expect(page).toHaveURL('\u002Fdashboard');\n  });\n\n  test('错误凭据显示提示', async ({ page }) => {\n    await loginPage.login('admin@example.com', 'wrong-password');\n    await expect(page.getByRole('alert')).toContainText('密码错误');\n    await expect(page).toHaveURL('\u002Flogin');\n  });\n\n  test('未登录重定向到登录页', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await expect(page).toHaveURL(\u002F\\\u002Flogin\u002F);\n  });\n});\n```\n\n### 5.3 表单验证\n\n```typescript\ntest.describe('表单验证', () => {\n  test('必填字段为空时显示错误', async ({ page }) => {\n    await page.goto('\u002Fusers\u002Fnew');\n    await page.getByRole('button', { name: '提交' }).click();\n\n    await expect(page.getByText('姓名不能为空')).toBeVisible();\n    await expect(page.getByText('邮箱不能为空')).toBeVisible();\n  });\n\n  test('邮箱格式错误时显示提示', async ({ page }) => {\n    await page.goto('\u002Fusers\u002Fnew');\n    await page.getByLabel('邮箱').fill('invalid-email');\n    await page.getByLabel('邮箱').blur();\n\n    await expect(page.getByText('邮箱格式不正确')).toBeVisible();\n  });\n});\n```\n\n---\n\n## 6. 视觉回归测试\n\n### 6.1 截图对比\n\n```typescript\ntest('首页视觉回归', async ({ page }) => {\n  await page.goto('\u002F');\n  \u002F\u002F 等待动态内容稳定\n  await page.waitForLoadState('networkidle');\n  await expect(page).toHaveScreenshot('homepage.png', {\n    maxDiffPixelRatio: 0.01,\n  });\n});\n\ntest('组件视觉回归', async ({ page }) => {\n  await page.goto('\u002Fcomponents\u002Fbutton');\n  const button = page.getByTestId('primary-button');\n  await expect(button).toHaveScreenshot('primary-button.png');\n});\n```\n\n### 6.2 更新基线\n\n```bash\n# 更新所有截图基线\nnpx playwright test --update-snapshots\n\n# 更新指定测试的截图\nnpx playwright test homepage.spec.ts --update-snapshots\n```\n\n### 6.3 注意事项\n\n- 截图基线需提交到 Git\n- 不同 OS 渲染有差异，CI 中使用 Docker 保证一致性\n- 对动态内容（时间、随机数据）需 Mock 后再截图\n- `maxDiffPixelRatio` 容忍微小渲染差异（抗锯齿等）\n\n---\n\n## 7. 多浏览器和移动端测试\n\n### 7.1 配置多 project\n\n```typescript\n\u002F\u002F playwright.config.ts 中的 projects 已覆盖\n\u002F\u002F 可根据项目需要选择性启用：\n\nprojects: [\n  \u002F\u002F 桌面浏览器\n  { name: 'chromium', use: { ...devices['Desktop Chrome'] } },\n  { name: 'firefox', use: { ...devices['Desktop Firefox'] } },\n  { name: 'webkit', use: { ...devices['Desktop Safari'] } },\n\n  \u002F\u002F 移动端视口\n  { name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },\n  { name: 'mobile-safari', use: { ...devices['iPhone 13'] } },\n\n  \u002F\u002F 平板\n  { name: 'tablet', use: { ...devices['iPad Pro 11'] } },\n];\n```\n\n### 7.2 按 project 运行\n\n```bash\n# 只跑 Chromium\nnpx playwright test --project=chromium\n\n# 只跑移动端\nnpx playwright test --project=mobile-chrome --project=mobile-safari\n```\n\n### 7.3 响应式断言\n\n```typescript\ntest('移动端显示汉堡菜单', async ({ page, isMobile }) => {\n  await page.goto('\u002F');\n  if (isMobile) {\n    await expect(page.getByTestId('hamburger-menu')).toBeVisible();\n    await expect(page.getByTestId('desktop-nav')).not.toBeVisible();\n  } else {\n    await expect(page.getByTestId('desktop-nav')).toBeVisible();\n    await expect(page.getByTestId('hamburger-menu')).not.toBeVisible();\n  }\n});\n```\n\n---\n\n## 8. 测试数据管理\n\n### 8.1 数据种子（Seed）\n\n```typescript\n\u002F\u002F e2e\u002Fhelpers\u002Fseed.ts\nimport { request } from '@playwright\u002Ftest';\n\nexport async function seedTestData(baseURL: string) {\n  const api = await request.newContext({ baseURL });\n  await api.post('\u002Fapi\u002Ftest\u002Fseed', {\n    data: {\n      users: [\n        { name: '测试管理员', email: 'admin@test.com', role: 'admin' },\n        { name: '测试用户', email: 'user@test.com', role: 'user' },\n      ],\n    },\n  });\n  await api.dispose();\n}\n```\n\n### 8.2 数据清理\n\n```typescript\n\u002F\u002F e2e\u002Fhelpers\u002Fcleanup.ts\nimport { request } from '@playwright\u002Ftest';\n\nexport async function cleanupTestData(baseURL: string) {\n  const api = await request.newContext({ baseURL });\n  await api.post('\u002Fapi\u002Ftest\u002Fcleanup');\n  await api.dispose();\n}\n```\n\n### 8.3 在 Global Setup\u002FTeardown 中使用\n\n```typescript\n\u002F\u002F e2e\u002Fglobal-setup.ts\nimport { seedTestData } from '.\u002Fhelpers\u002Fseed';\n\nasync function globalSetup() {\n  await seedTestData('http:\u002F\u002Flocalhost:3000');\n}\nexport default globalSetup;\n\n\u002F\u002F e2e\u002Fglobal-teardown.ts\nimport { cleanupTestData } from '.\u002Fhelpers\u002Fcleanup';\n\nasync function globalTeardown() {\n  await cleanupTestData('http:\u002F\u002Flocalhost:3000');\n}\nexport default globalTeardown;\n```\n\n### 8.4 原则\n\n| 原则              | 说明                                    |\n| ----------------- | --------------------------------------- |\n| **测试隔离**      | 每个测试独立运行，不依赖其他测试的数据  |\n| **可重复**        | 多次运行结果一致                        |\n| **快速清理**      | 使用 API 清理而非 UI 操作               |\n| **避免硬编码 ID** | 使用动态创建的数据，不依赖数据库自增 ID |\n\n---\n\n## 9. CI\u002FCD 集成\n\n### 9.1 GitHub Actions\n\n```yaml\n# .github\u002Fworkflows\u002Fe2e.yml\nname: E2E Tests\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  e2e:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n\n      - name: Install dependencies\n        run: npm ci\n\n      - name: Install Playwright browsers\n        run: npx playwright install --with-deps\n\n      - name: Build application\n        run: npm run build\n\n      - name: Run E2E tests\n        run: npx playwright test\n\n      - name: Upload test results\n        if: ${{ !cancelled() }}\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: playwright-report\n          path: e2e\u002Fplaywright-report\u002F\n          retention-days: 30\n\n      - name: Upload trace files\n        if: failure()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: playwright-traces\n          path: e2e\u002Ftest-results\u002F\n          retention-days: 7\n```\n\n### 9.2 Docker 一致性\n\n```dockerfile\n# e2e\u002FDockerfile\nFROM mcr.microsoft.com\u002Fplaywright:v1.49.0-noble\nWORKDIR \u002Fapp\nCOPY package*.json .\u002F\nRUN npm ci\nCOPY . .\nRUN npm run build\nCMD [\"npx\", \"playwright\", \"test\"]\n```\n\n### 9.3 CI 关键配置\n\n| 配置       | CI 值             | 原因                           |\n| ---------- | ----------------- | ------------------------------ |\n| `workers`  | 1                 | CI 资源有限，避免争抢          |\n| `retries`  | 1                 | 减少 flaky 误报                |\n| `reporter` | `github` + `html` | GitHub PR 行内注释 + HTML 归档 |\n| `trace`    | `on-first-retry`  | 只在重试时录制，节省空间       |\n\n---\n\n## 10. 调试技巧\n\n### 10.1 UI 模式（开发首选）\n\n```bash\n# 打开可视化调试界面\nnpx playwright test --ui\n```\n\n### 10.2 Trace Viewer\n\n```bash\n# 查看失败测试的 trace\nnpx playwright show-trace e2e\u002Ftest-results\u002Fspecs-auth-login-spec-ts\u002Ftrace.zip\n```\n\nTrace Viewer 提供：\n- 时间线上的每一步操作\n- DOM 快照\n- 网络请求日志\n- 控制台输出\n\n### 10.3 Debug 模式\n\n```bash\n# 逐步执行，自动暂停\nnpx playwright test --debug\n\n# 指定测试文件\nnpx playwright test login.spec.ts --debug\n```\n\n### 10.4 代码中暂停\n\n```typescript\ntest('调试用', async ({ page }) => {\n  await page.goto('\u002Flogin');\n  await page.pause(); \u002F\u002F 打开 Inspector，手动操作\n  \u002F\u002F ...\n});\n```\n\n### 10.5 录制生成测试\n\n```bash\n# 打开浏览器录制，自动生成代码\nnpx playwright codegen http:\u002F\u002Flocalhost:3000\n```\n\n### 10.6 常见 Flaky 原因及修复\n\n| 原因         | 症状                  | 修复                                   |\n| ------------ | --------------------- | -------------------------------------- |\n| 动画未完成   | 元素找到但点击无效    | 等待动画完成或禁用动画                 |\n| 网络请求延迟 | 元素内容未更新        | 使用 `waitForResponse`                 |\n| 竞态条件     | 间歇性失败            | 使用 `expect().toBeVisible()` 自动等待 |\n| 数据未就绪   | 列表为空              | 使用 `waitForLoadState('networkidle')` |\n| 时间依赖     | 日期\u002F时间相关断言失败 | Mock 时间或使用范围断言                |\n\n---\n\n## 11. 与 Boss 流水线门禁集成\n\n### 11.1 Gate 1 E2E 检查项\n\nBoss 流水线的 Gate 1 门禁要求 E2E 测试满足：\n\n| 检查项        | 要求                            | 说明                   |\n| ------------- | ------------------------------- | ---------------------- |\n| E2E 测试存在  | `e2e\u002F` 或 `tests\u002Fe2e\u002F` 目录非空 | 不能只有单元测试       |\n| 关键路径覆盖  | CRUD + 认证 + 核心业务流程      | 至少 5 个核心用户操作  |\n| 全部通过      | 无失败用例                      | 失败则门禁不通过       |\n| 真实 API 证据 | 核心路径不能只有 Mock           | Mock-only 标记为未验证 |\n\n### 11.2 执行命令\n\n```bash\n# 门禁检查时执行\nnpx playwright test --reporter=json --output=e2e\u002Ftest-results\n\n# 仅核心路径（CI 加速）\nnpx playwright test --grep @critical\n\n# 完整套件\nnpx playwright test\n```\n\n### 11.3 测试标签\n\n使用标签标记测试优先级，门禁可按标签选择性执行：\n\n```typescript\ntest('@critical 登录流程', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@critical 核心业务流程', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@smoke 首页加载', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@regression 边界情况', async ({ page }) => {\n  \u002F* ... *\u002F\n});\n```\n\n```bash\n# Gate 1 只跑 critical\nnpx playwright test --grep @critical\n\n# 完整回归\nnpx playwright test\n```\n\n---\n\n## 12. 检查清单\n\nAgent 编写 E2E 测试时，对照以下清单确认完整性：\n- [ ] `playwright.config.ts` 已配置（baseURL、webServer、projects）\n- [ ] Page Object Model 已建立（每个核心页面一个 POM）\n- [ ] 定位器使用语义化方法（`getByRole` > `getByTestId` > CSS）\n- [ ] 认证状态已配置复用（`storageState`）\n- [ ] 关键用户路径已覆盖（CRUD + 认证 + 核心业务）\n- [ ] 错误状态和边界条件已测试（空数据、网络错误、表单验证）\n- [ ] 核心路径使用真实 API（非 Mock-only）\n- [ ] CI 配置已就绪（GitHub Actions \u002F 其他）\n- [ ] 测试产物目录已加入 `.gitignore`（`test-results\u002F`、`playwright-report\u002F`）\n- [ ] 截图基线已提交（如使用视觉回归）\n\n## 输出要求\n\n使用本方法论后，Agent 应产出：\n1. **`playwright.config.ts`**：完整配置\n2. **`e2e\u002Fpages\u002F*.page.ts`**：Page Object Model\n3. **`e2e\u002Fspecs\u002F**\u002F*.spec.ts`**：测试用例（覆盖关键路径）\n4. **认证 fixture**：`storageState` 或 global-setup\n5. **CI 配置**：GitHub Actions 或等价 CI 流程\n6. **`.gitignore` 更新**：排除测试产物目录\n","# Playwright E2E 测试方法论\n\n## 适用场景\n\n- Web 项目需要编写端到端测试\n- 门禁（Gate 1）要求 E2E 测试通过\n- 需要覆盖关键用户流程的自动化验证\n- 需要多浏览器\u002F多视口兼容性验证\n- 需要视觉回归测试\n\n---\n\n## 1. 项目初始化\n\n### 1.1 安装\n\n```bash\n# 新项目初始化（推荐）\nnpm init playwright@latest\n\n# 已有项目添加\nnpm install -D @playwright\u002Ftest\nnpx playwright install\n```\n\n### 1.2 配置文件（`playwright.config.ts`）\n\n```typescript\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Fe2e',\n  \u002F\u002F 测试产物目录\n  outputDir: '.\u002Fe2e\u002Ftest-results',\n\n  \u002F\u002F 全局超时\n  timeout: 30_000,\n  expect: { timeout: 5_000 },\n\n  \u002F\u002F 并行执行\n  fullyParallel: true,\n  workers: process.env.CI ? 1 : undefined,\n\n  \u002F\u002F 失败重试（CI 中重试一次减少 flaky）\n  retries: process.env.CI ? 1 : 0,\n\n  \u002F\u002F 报告\n  reporter: [\n    ['html', { outputFolder: '.\u002Fe2e\u002Fplaywright-report' }],\n    ['json', { outputFile: '.\u002Fe2e\u002Ftest-results\u002Fresults.json' }],\n    \u002F\u002F CI 中额外输出到 stdout\n    ...(process.env.CI ? [['github'] as const] : []),\n  ],\n\n  \u002F\u002F 全局配置\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    \u002F\u002F 失败时自动截图\n    screenshot: 'only-on-failure',\n    \u002F\u002F 失败时录制 trace\n    trace: 'on-first-retry',\n    \u002F\u002F 失败时录制视频\n    video: 'on-first-retry',\n  },\n\n  \u002F\u002F 多浏览器 + 移动端视口\n  projects: [\n    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },\n    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },\n    { name: 'webkit', use: { ...devices['Desktop Safari'] } },\n    { name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },\n    { name: 'mobile-safari', use: { ...devices['iPhone 13'] } },\n  ],\n\n  \u002F\u002F 开发服务器自动启动\n  webServer: {\n    command: 'npm run dev',\n    url: 'http:\u002F\u002Flocalhost:3000',\n    reuseExistingServer: !process.env.CI,\n    timeout: 120_000,\n  },\n});\n```\n\n**关键配置说明**：\n\n| 配置项          | 作用                   | 建议值            |\n| --------------- | ---------------------- | ----------------- |\n| `fullyParallel` | 测试文件间并行执行     | `true`            |\n| `workers`       | 并行 worker 数         | CI 为 1，本地默认 |\n| `retries`       | 失败重试次数           | CI 为 1，本地为 0 |\n| `trace`         | 失败时生成可视化时间线 | `on-first-retry`  |\n| `webServer`     | 自动启动开发服务器     | 必须配置          |\n\n### 1.3 目录结构\n\n```\ne2e\u002F\n├── playwright.config.ts        # 配置文件（或放在项目根目录）\n├── fixtures\u002F                   # 自定义 fixtures\n│   ├── base.ts                 # 扩展 base test\n│   └── auth.ts                 # 认证 fixture\n├── pages\u002F                      # Page Object Models\n│   ├── login.page.ts\n│   ├── dashboard.page.ts\n│   └── components\u002F             # 可复用组件 POM\n│       ├── navbar.component.ts\n│       └── modal.component.ts\n├── specs\u002F                      # 测试用例\n│   ├── auth\u002F\n│   │   ├── login.spec.ts\n│   │   └── register.spec.ts\n│   ├── dashboard\u002F\n│   │   └── dashboard.spec.ts\n│   └── crud\u002F\n│       └── user-management.spec.ts\n├── helpers\u002F                    # 测试工具\n│   ├── seed.ts                 # 数据种子\n│   └── cleanup.ts              # 数据清理\n├── test-results\u002F               # 测试产物（gitignore）\n└── playwright-report\u002F          # HTML 报告（gitignore）\n```\n\n---\n\n## 2. Page Object Model（POM）\n\n### 2.1 核心原则\n\n- **每个页面一个 POM 类**：封装定位器和操作方法\n- **不暴露 Locator**：外部只调用语义化方法\n- **组件级复用**：导航栏、弹窗等提取为独立组件 POM\n\n### 2.2 基础 POM\n\n```typescript\n\u002F\u002F e2e\u002Fpages\u002Flogin.page.ts\nimport { type Page, type Locator } from '@playwright\u002Ftest';\n\nexport class LoginPage {\n  private readonly emailInput: Locator;\n  private readonly passwordInput: Locator;\n  private readonly submitButton: Locator;\n  private readonly errorMessage: Locator;\n\n  constructor(private readonly page: Page) {\n    this.emailInput = page.getByLabel('邮箱');\n    this.passwordInput = page.getByLabel('密码');\n    this.submitButton = page.getByRole('button', { name: '登录' });\n    this.errorMessage = page.getByRole('alert');\n  }\n\n  async goto() {\n    await this.page.goto('\u002Flogin');\n  }\n\n  async login(email: string, password: string) {\n    await this.emailInput.fill(email);\n    await this.passwordInput.fill(password);\n    await this.submitButton.click();\n  }\n\n  async getErrorMessage() {\n    return this.errorMessage.textContent();\n  }\n}\n```\n\n### 2.3 组件 POM\n\n```typescript\n\u002F\u002F e2e\u002Fpages\u002Fcomponents\u002Fnavbar.component.ts\nimport { type Page, type Locator } from '@playwright\u002Ftest';\n\nexport class NavbarComponent {\n  private readonly userMenu: Locator;\n  private readonly logoutButton: Locator;\n\n  constructor(private readonly page: Page) {\n    this.userMenu = page.getByTestId('user-menu');\n    this.logoutButton = page.getByRole('menuitem', { name: '退出登录' });\n  }\n\n  async logout() {\n    await this.userMenu.click();\n    await this.logoutButton.click();\n  }\n\n  async getUserDisplayName() {\n    return this.userMenu.textContent();\n  }\n}\n```\n\n### 2.4 定位器优先级\n\n选择定位器时遵循以下优先级（可靠性从高到低）：\n\n| 优先级 | 方法               | 示例                                    | 说明               |\n| ------ | ------------------ | --------------------------------------- | ------------------ |\n| 1      | `getByRole`        | `getByRole('button', { name: '提交' })` | 无障碍语义，最稳定 |\n| 2      | `getByLabel`       | `getByLabel('邮箱')`                    | 表单元素首选       |\n| 3      | `getByPlaceholder` | `getByPlaceholder('请输入邮箱')`        | 备选               |\n| 4      | `getByText`        | `getByText('欢迎回来')`                 | 静态文本           |\n| 5      | `getByTestId`      | `getByTestId('submit-btn')`             | 无语义标记时的兜底 |\n| 6      | CSS\u002FXPath          | `page.locator('.btn-primary')`          | **尽量避免**       |\n\n---\n\n## 3. 认证状态复用\n\n### 3.1 Global Setup 方式\n\n```typescript\n\u002F\u002F e2e\u002Fglobal-setup.ts\nimport { chromium, type FullConfig } from '@playwright\u002Ftest';\n\nasync function globalSetup(config: FullConfig) {\n  const browser = await chromium.launch();\n  const page = await browser.newPage();\n\n  \u002F\u002F 执行登录\n  await page.goto('http:\u002F\u002Flocalhost:3000\u002Flogin');\n  await page.getByLabel('邮箱').fill('admin@example.com');\n  await page.getByLabel('密码').fill('password');\n  await page.getByRole('button', { name: '登录' }).click();\n  await page.waitForURL('\u002Fdashboard');\n\n  \u002F\u002F 保存认证状态\n  await page.context().storageState({ path: '.\u002Fe2e\u002F.auth\u002Fadmin.json' });\n  await browser.close();\n}\n\nexport default globalSetup;\n```\n\n**配置引用**：\n\n```typescript\n\u002F\u002F playwright.config.ts\nexport default defineConfig({\n  globalSetup: '.\u002Fe2e\u002Fglobal-setup.ts',\n  projects: [\n    \u002F\u002F 不带认证的测试\n    { name: 'public', testMatch: \u002Fpublic\\.spec\\.ts\u002F },\n    \u002F\u002F 带认证的测试\n    {\n      name: 'authenticated',\n      use: { storageState: '.\u002Fe2e\u002F.auth\u002Fadmin.json' },\n      testIgnore: \u002Fpublic\\.spec\\.ts\u002F,\n    },\n  ],\n});\n```\n\n### 3.2 多角色认证\n\n```typescript\n\u002F\u002F e2e\u002Ffixtures\u002Fauth.ts\nimport { test as base } from '@playwright\u002Ftest';\n\ntype AuthFixtures = {\n  adminPage: Page;\n  userPage: Page;\n};\n\nexport const test = base.extend\u003CAuthFixtures>({\n  adminPage: async ({ browser }, use) => {\n    const context = await browser.newContext({\n      storageState: '.\u002Fe2e\u002F.auth\u002Fadmin.json',\n    });\n    const page = await context.newPage();\n    await use(page);\n    await context.close();\n  },\n  userPage: async ({ browser }, use) => {\n    const context = await browser.newContext({\n      storageState: '.\u002Fe2e\u002F.auth\u002Fuser.json',\n    });\n    const page = await context.newPage();\n    await use(page);\n    await context.close();\n  },\n});\n```\n\n---\n\n## 4. API Mocking\n\n### 4.1 使用 `page.route` 拦截请求\n\n```typescript\ntest('显示用户列表（API Mock）', async ({ page }) => {\n  \u002F\u002F 拦截 API 请求\n  await page.route('\u002Fapi\u002Fusers', async (route) => {\n    await route.fulfill({\n      status: 200,\n      contentType: 'application\u002Fjson',\n      body: JSON.stringify([\n        { id: 1, name: '张三', email: 'zhang@example.com' },\n        { id: 2, name: '李四', email: 'li@example.com' },\n      ]),\n    });\n  });\n\n  await page.goto('\u002Fusers');\n  await expect(page.getByText('张三')).toBeVisible();\n  await expect(page.getByText('李四')).toBeVisible();\n});\n```\n\n### 4.2 模拟错误响应\n\n```typescript\ntest('API 失败时显示错误提示', async ({ page }) => {\n  await page.route('\u002Fapi\u002Fusers', async (route) => {\n    await route.fulfill({ status: 500, body: 'Internal Server Error' });\n  });\n\n  await page.goto('\u002Fusers');\n  await expect(page.getByText('加载失败')).toBeVisible();\n  await expect(page.getByRole('button', { name: '重试' })).toBeVisible();\n});\n```\n\n### 4.3 Mock 与真实请求混合\n\n```typescript\ntest('部分 API Mock', async ({ page }) => {\n  \u002F\u002F 只 Mock 第三方支付接口，其余走真实请求\n  await page.route('**\u002Fapi\u002Fpayment\u002F**', async (route) => {\n    await route.fulfill({\n      status: 200,\n      body: JSON.stringify({ success: true, transactionId: 'mock-tx-001' }),\n    });\n  });\n\n  await page.goto('\u002Fcheckout');\n  \u002F\u002F ... 执行支付流程\n});\n```\n\n### 4.4 何时用 Mock vs 真实 API\n\n| 场景                     | 建议                             |\n| ------------------------ | -------------------------------- |\n| 核心用户路径             | **真实 API**（关键路径证据规则） |\n| 第三方服务（支付、邮件） | Mock                             |\n| 错误\u002F边界状态            | Mock                             |\n| 加载状态、空数据         | Mock                             |\n| 数据量大的列表\u002F分页      | Mock + 至少一条真实路径          |\n\n⚠️ **Boss 门禁规则**：核心用户路径只由 Mock 证明的，必须标记为**未验证**，不能作为发布证据。\n\n---\n\n## 5. 关键用户流程测试（必须覆盖）\n\n### 5.1 CRUD 完整流程\n\n```typescript\n\u002F\u002F e2e\u002Fspecs\u002Fcrud\u002Fuser-management.spec.ts\nimport { test, expect } from '@playwright\u002Ftest';\nimport { UserListPage } from '..\u002F..\u002Fpages\u002Fuser-list.page';\nimport { UserFormPage } from '..\u002F..\u002Fpages\u002Fuser-form.page';\n\ntest.describe('用户管理 CRUD', () => {\n  let userList: UserListPage;\n  let userForm: UserFormPage;\n\n  test.beforeEach(async ({ page }) => {\n    userList = new UserListPage(page);\n    userForm = new UserFormPage(page);\n    await userList.goto();\n  });\n\n  test('创建 → 编辑 → 删除完整流程', async ({ page }) => {\n    \u002F\u002F 创建\n    await userList.clickAddUser();\n    await userForm.fillName('测试用户');\n    await userForm.fillEmail('test@example.com');\n    await userForm.submit();\n    await expect(page.getByText('测试用户')).toBeVisible();\n\n    \u002F\u002F 编辑\n    await userList.editUser('测试用户');\n    await userForm.fillName('修改后的用户');\n    await userForm.submit();\n    await expect(page.getByText('修改后的用户')).toBeVisible();\n    await expect(page.getByText('测试用户')).not.toBeVisible();\n\n    \u002F\u002F 删除\n    await userList.deleteUser('修改后的用户');\n    await userList.confirmDelete();\n    await expect(page.getByText('修改后的用户')).not.toBeVisible();\n  });\n\n  test('列表分页展示', async ({ page }) => {\n    await expect(userList.getTable()).toBeVisible();\n    await userList.goToNextPage();\n    await expect(page).toHaveURL(\u002Fpage=2\u002F);\n  });\n\n  test('空列表提示', async ({ page }) => {\n    \u002F\u002F 使用 route mock 空数据场景\n    await page.route('\u002Fapi\u002Fusers*', (route) =>\n      route.fulfill({ status: 200, body: JSON.stringify({ data: [], total: 0 }) }),\n    );\n    await page.reload();\n    await expect(page.getByText('暂无数据')).toBeVisible();\n  });\n});\n```\n\n### 5.2 认证流程\n\n```typescript\n\u002F\u002F e2e\u002Fspecs\u002Fauth\u002Flogin.spec.ts\nimport { test, expect } from '@playwright\u002Ftest';\nimport { LoginPage } from '..\u002F..\u002Fpages\u002Flogin.page';\n\ntest.describe('登录', () => {\n  let loginPage: LoginPage;\n\n  test.beforeEach(async ({ page }) => {\n    loginPage = new LoginPage(page);\n    await loginPage.goto();\n  });\n\n  test('正确凭据成功登录', async ({ page }) => {\n    await loginPage.login('admin@example.com', 'password');\n    await expect(page).toHaveURL('\u002Fdashboard');\n  });\n\n  test('错误凭据显示提示', async ({ page }) => {\n    await loginPage.login('admin@example.com', 'wrong-password');\n    await expect(page.getByRole('alert')).toContainText('密码错误');\n    await expect(page).toHaveURL('\u002Flogin');\n  });\n\n  test('未登录重定向到登录页', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await expect(page).toHaveURL(\u002F\\\u002Flogin\u002F);\n  });\n});\n```\n\n### 5.3 表单验证\n\n```typescript\ntest.describe('表单验证', () => {\n  test('必填字段为空时显示错误', async ({ page }) => {\n    await page.goto('\u002Fusers\u002Fnew');\n    await page.getByRole('button', { name: '提交' }).click();\n\n    await expect(page.getByText('姓名不能为空')).toBeVisible();\n    await expect(page.getByText('邮箱不能为空')).toBeVisible();\n  });\n\n  test('邮箱格式错误时显示提示', async ({ page }) => {\n    await page.goto('\u002Fusers\u002Fnew');\n    await page.getByLabel('邮箱').fill('invalid-email');\n    await page.getByLabel('邮箱').blur();\n\n    await expect(page.getByText('邮箱格式不正确')).toBeVisible();\n  });\n});\n```\n\n---\n\n## 6. 视觉回归测试\n\n### 6.1 截图对比\n\n```typescript\ntest('首页视觉回归', async ({ page }) => {\n  await page.goto('\u002F');\n  \u002F\u002F 等待动态内容稳定\n  await page.waitForLoadState('networkidle');\n  await expect(page).toHaveScreenshot('homepage.png', {\n    maxDiffPixelRatio: 0.01,\n  });\n});\n\ntest('组件视觉回归', async ({ page }) => {\n  await page.goto('\u002Fcomponents\u002Fbutton');\n  const button = page.getByTestId('primary-button');\n  await expect(button).toHaveScreenshot('primary-button.png');\n});\n```\n\n### 6.2 更新基线\n\n```bash\n# 更新所有截图基线\nnpx playwright test --update-snapshots\n\n# 更新指定测试的截图\nnpx playwright test homepage.spec.ts --update-snapshots\n```\n\n### 6.3 注意事项\n\n- 截图基线需提交到 Git\n- 不同 OS 渲染有差异，CI 中使用 Docker 保证一致性\n- 对动态内容（时间、随机数据）需 Mock 后再截图\n- `maxDiffPixelRatio` 容忍微小渲染差异（抗锯齿等）\n\n---\n\n## 7. 多浏览器和移动端测试\n\n### 7.1 配置多 project\n\n```typescript\n\u002F\u002F playwright.config.ts 中的 projects 已覆盖\n\u002F\u002F 可根据项目需要选择性启用：\n\nprojects: [\n  \u002F\u002F 桌面浏览器\n  { name: 'chromium', use: { ...devices['Desktop Chrome'] } },\n  { name: 'firefox', use: { ...devices['Desktop Firefox'] } },\n  { name: 'webkit', use: { ...devices['Desktop Safari'] } },\n\n  \u002F\u002F 移动端视口\n  { name: 'mobile-chrome', use: { ...devices['Pixel 5'] } },\n  { name: 'mobile-safari', use: { ...devices['iPhone 13'] } },\n\n  \u002F\u002F 平板\n  { name: 'tablet', use: { ...devices['iPad Pro 11'] } },\n];\n```\n\n### 7.2 按 project 运行\n\n```bash\n# 只跑 Chromium\nnpx playwright test --project=chromium\n\n# 只跑移动端\nnpx playwright test --project=mobile-chrome --project=mobile-safari\n```\n\n### 7.3 响应式断言\n\n```typescript\ntest('移动端显示汉堡菜单', async ({ page, isMobile }) => {\n  await page.goto('\u002F');\n  if (isMobile) {\n    await expect(page.getByTestId('hamburger-menu')).toBeVisible();\n    await expect(page.getByTestId('desktop-nav')).not.toBeVisible();\n  } else {\n    await expect(page.getByTestId('desktop-nav')).toBeVisible();\n    await expect(page.getByTestId('hamburger-menu')).not.toBeVisible();\n  }\n});\n```\n\n---\n\n## 8. 测试数据管理\n\n### 8.1 数据种子（Seed）\n\n```typescript\n\u002F\u002F e2e\u002Fhelpers\u002Fseed.ts\nimport { request } from '@playwright\u002Ftest';\n\nexport async function seedTestData(baseURL: string) {\n  const api = await request.newContext({ baseURL });\n  await api.post('\u002Fapi\u002Ftest\u002Fseed', {\n    data: {\n      users: [\n        { name: '测试管理员', email: 'admin@test.com', role: 'admin' },\n        { name: '测试用户', email: 'user@test.com', role: 'user' },\n      ],\n    },\n  });\n  await api.dispose();\n}\n```\n\n### 8.2 数据清理\n\n```typescript\n\u002F\u002F e2e\u002Fhelpers\u002Fcleanup.ts\nimport { request } from '@playwright\u002Ftest';\n\nexport async function cleanupTestData(baseURL: string) {\n  const api = await request.newContext({ baseURL });\n  await api.post('\u002Fapi\u002Ftest\u002Fcleanup');\n  await api.dispose();\n}\n```\n\n### 8.3 在 Global Setup\u002FTeardown 中使用\n\n```typescript\n\u002F\u002F e2e\u002Fglobal-setup.ts\nimport { seedTestData } from '.\u002Fhelpers\u002Fseed';\n\nasync function globalSetup() {\n  await seedTestData('http:\u002F\u002Flocalhost:3000');\n}\nexport default globalSetup;\n\n\u002F\u002F e2e\u002Fglobal-teardown.ts\nimport { cleanupTestData } from '.\u002Fhelpers\u002Fcleanup';\n\nasync function globalTeardown() {\n  await cleanupTestData('http:\u002F\u002Flocalhost:3000');\n}\nexport default globalTeardown;\n```\n\n### 8.4 原则\n\n| 原则              | 说明                                    |\n| ----------------- | --------------------------------------- |\n| **测试隔离**      | 每个测试独立运行，不依赖其他测试的数据  |\n| **可重复**        | 多次运行结果一致                        |\n| **快速清理**      | 使用 API 清理而非 UI 操作               |\n| **避免硬编码 ID** | 使用动态创建的数据，不依赖数据库自增 ID |\n\n---\n\n## 9. CI\u002FCD 集成\n\n### 9.1 GitHub Actions\n\n```yaml\n# .github\u002Fworkflows\u002Fe2e.yml\nname: E2E Tests\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  e2e:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n\n      - name: Install dependencies\n        run: npm ci\n\n      - name: Install Playwright browsers\n        run: npx playwright install --with-deps\n\n      - name: Build application\n        run: npm run build\n\n      - name: Run E2E tests\n        run: npx playwright test\n\n      - name: Upload test results\n        if: ${{ !cancelled() }}\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: playwright-report\n          path: e2e\u002Fplaywright-report\u002F\n          retention-days: 30\n\n      - name: Upload trace files\n        if: failure()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: playwright-traces\n          path: e2e\u002Ftest-results\u002F\n          retention-days: 7\n```\n\n### 9.2 Docker 一致性\n\n```dockerfile\n# e2e\u002FDockerfile\nFROM mcr.microsoft.com\u002Fplaywright:v1.49.0-noble\nWORKDIR \u002Fapp\nCOPY package*.json .\u002F\nRUN npm ci\nCOPY . .\nRUN npm run build\nCMD [\"npx\", \"playwright\", \"test\"]\n```\n\n### 9.3 CI 关键配置\n\n| 配置       | CI 值             | 原因                           |\n| ---------- | ----------------- | ------------------------------ |\n| `workers`  | 1                 | CI 资源有限，避免争抢          |\n| `retries`  | 1                 | 减少 flaky 误报                |\n| `reporter` | `github` + `html` | GitHub PR 行内注释 + HTML 归档 |\n| `trace`    | `on-first-retry`  | 只在重试时录制，节省空间       |\n\n---\n\n## 10. 调试技巧\n\n### 10.1 UI 模式（开发首选）\n\n```bash\n# 打开可视化调试界面\nnpx playwright test --ui\n```\n\n### 10.2 Trace Viewer\n\n```bash\n# 查看失败测试的 trace\nnpx playwright show-trace e2e\u002Ftest-results\u002Fspecs-auth-login-spec-ts\u002Ftrace.zip\n```\n\nTrace Viewer 提供：\n- 时间线上的每一步操作\n- DOM 快照\n- 网络请求日志\n- 控制台输出\n\n### 10.3 Debug 模式\n\n```bash\n# 逐步执行，自动暂停\nnpx playwright test --debug\n\n# 指定测试文件\nnpx playwright test login.spec.ts --debug\n```\n\n### 10.4 代码中暂停\n\n```typescript\ntest('调试用', async ({ page }) => {\n  await page.goto('\u002Flogin');\n  await page.pause(); \u002F\u002F 打开 Inspector，手动操作\n  \u002F\u002F ...\n});\n```\n\n### 10.5 录制生成测试\n\n```bash\n# 打开浏览器录制，自动生成代码\nnpx playwright codegen http:\u002F\u002Flocalhost:3000\n```\n\n### 10.6 常见 Flaky 原因及修复\n\n| 原因         | 症状                  | 修复                                   |\n| ------------ | --------------------- | -------------------------------------- |\n| 动画未完成   | 元素找到但点击无效    | 等待动画完成或禁用动画                 |\n| 网络请求延迟 | 元素内容未更新        | 使用 `waitForResponse`                 |\n| 竞态条件     | 间歇性失败            | 使用 `expect().toBeVisible()` 自动等待 |\n| 数据未就绪   | 列表为空              | 使用 `waitForLoadState('networkidle')` |\n| 时间依赖     | 日期\u002F时间相关断言失败 | Mock 时间或使用范围断言                |\n\n---\n\n## 11. 与 Boss 流水线门禁集成\n\n### 11.1 Gate 1 E2E 检查项\n\nBoss 流水线的 Gate 1 门禁要求 E2E 测试满足：\n\n| 检查项        | 要求                            | 说明                   |\n| ------------- | ------------------------------- | ---------------------- |\n| E2E 测试存在  | `e2e\u002F` 或 `tests\u002Fe2e\u002F` 目录非空 | 不能只有单元测试       |\n| 关键路径覆盖  | CRUD + 认证 + 核心业务流程      | 至少 5 个核心用户操作  |\n| 全部通过      | 无失败用例                      | 失败则门禁不通过       |\n| 真实 API 证据 | 核心路径不能只有 Mock           | Mock-only 标记为未验证 |\n\n### 11.2 执行命令\n\n```bash\n# 门禁检查时执行\nnpx playwright test --reporter=json --output=e2e\u002Ftest-results\n\n# 仅核心路径（CI 加速）\nnpx playwright test --grep @critical\n\n# 完整套件\nnpx playwright test\n```\n\n### 11.3 测试标签\n\n使用标签标记测试优先级，门禁可按标签选择性执行：\n\n```typescript\ntest('@critical 登录流程', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@critical 核心业务流程', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@smoke 首页加载', async ({ page }) => {\n  \u002F* ... *\u002F\n});\ntest('@regression 边界情况', async ({ page }) => {\n  \u002F* ... *\u002F\n});\n```\n\n```bash\n# Gate 1 只跑 critical\nnpx playwright test --grep @critical\n\n# 完整回归\nnpx playwright test\n```\n\n---\n\n## 12. 检查清单\n\nAgent 编写 E2E 测试时，对照以下清单确认完整性：\n- [ ] `playwright.config.ts` 已配置（baseURL、webServer、projects）\n- [ ] Page Object Model 已建立（每个核心页面一个 POM）\n- [ ] 定位器使用语义化方法（`getByRole` > `getByTestId` > CSS）\n- [ ] 认证状态已配置复用（`storageState`）\n- [ ] 关键用户路径已覆盖（CRUD + 认证 + 核心业务）\n- [ ] 错误状态和边界条件已测试（空数据、网络错误、表单验证）\n- [ ] 核心路径使用真实 API（非 Mock-only）\n- [ ] CI 配置已就绪（GitHub Actions \u002F 其他）\n- [ ] 测试产物目录已加入 `.gitignore`（`test-results\u002F`、`playwright-report\u002F`）\n- [ ] 截图基线已提交（如使用视觉回归）\n\n## 输出要求\n\n使用本方法论后，Agent 应产出：\n1. **`playwright.config.ts`**：完整配置\n2. **`e2e\u002Fpages\u002F*.page.ts`**：Page Object Model\n3. **`e2e\u002Fspecs\u002F**\u002F*.spec.ts`**：测试用例（覆盖关键路径）\n4. **认证 fixture**：`storageState` 或 global-setup\n5. **CI 配置**：GitHub Actions 或等价 CI 流程\n6. **`.gitignore` 更新**：排除测试产物目录\n",{},"main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fe2e-playwright",491,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-14 14:06:13",{"source":7,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill e2e-playwright",{"tool":42,"command":43},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill e2e-playwright",{"tool":45,"command":46},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill e2e-playwright","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fe2e-playwright\u002FSKILL.md",true,[],[51,61,69,77,85,93],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":56,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":60},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":65,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":60},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":60},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":81,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":60},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":60},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":55,"licenseFileUrl":97,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":60},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]