playwright-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Playwright Testing

Playwright 测试

Workflow

工作流程

  1. Confirm Playwright setup and target app URL.
  2. Choose language (TypeScript or Python) based on repo.
  3. Record or author tests with stable selectors.
  4. Add assertions for key UI states and flows.
  5. Run tests and debug failures.
  1. 确认Playwright环境已搭建完成,并确定目标应用URL。
  2. 根据代码仓库选择开发语言(TypeScript或Python)。
  3. 录制或编写测试用例,使用稳定的选择器。
  4. 为关键UI状态与流程添加断言。
  5. 运行测试并调试失败用例。

Quick Intake (Ask/Confirm)

快速确认项(询问/确认)

  • Target environment (local dev server, staging URL, ephemeral preview).
  • Auth needs (anonymous vs logged-in roles) and how to obtain credentials safely.
  • State management (seeded DB? test accounts? reset between runs?).
  • CI expectations (headless, artifacts, retries, cross-browser).
  • 目标环境(本地开发服务器、预发布URL、临时预览环境)。
  • 认证需求(匿名访问 vs 登录角色)以及安全获取凭证的方式。
  • 状态管理(预填充数据库?测试账号?测试间是否需要重置状态?)。
  • CI环境预期配置(无头模式、产物留存、重试机制、跨浏览器测试)。

Setup

环境搭建

  • Install Playwright and browsers.
  • Use existing test config when present.
  • In CI, always install browsers explicitly (
    npx playwright install --with-deps
    ) after
    npm ci
    .
Common setup:
bash
undefined
  • 安装Playwright及对应浏览器。
  • 若已有测试配置文件,直接复用。
  • 在CI环境中,执行
    npm ci
    后务必显式安装浏览器(
    npx playwright install --with-deps
    )。
通用搭建命令:
bash
undefined

Node/TS

Node/TS

npm i -D @playwright/test npx playwright install --with-deps
npm i -D @playwright/test npx playwright install --with-deps

Python

Python

pip install pytest-playwright playwright install
undefined
pip install pytest-playwright playwright install
undefined

Test Authoring

测试用例编写

  • Prefer role-based or data-testid selectors.
  • Avoid brittle selectors tied to DOM structure.
  • Use
    expect
    for visible, enabled, or text states.
  • Prefer
    playwright codegen
    for quick prototypes, then harden selectors/assertions.
Rules of thumb:
  • Prefer
    getByRole
    /
    get_by_role
    and
    getByTestId
    /
    get_by_test_id
    .
  • Avoid XPath and deep CSS chains unless there is no stable alternative.
  • Avoid static sleeps (
    waitForTimeout
    /
    time.sleep
    ) in favor of web-first assertions.
  • Keep tests focused: one primary user outcome per test.
Authentication patterns:
  • For large suites, reuse authenticated state via
    storageState
    (keep out of git).
  • Use separate storage states for different roles (admin vs user) to avoid cross-test interference.
  • 优先使用基于角色或data-testid的选择器。
  • 避免依赖DOM结构的脆弱选择器。
  • 使用
    expect
    断言元素的可见性、启用状态或文本内容。
  • 可先用
    playwright codegen
    快速生成原型,再优化选择器与断言逻辑。
编写准则:
  • 优先使用
    getByRole
    /
    get_by_role
    getByTestId
    /
    get_by_test_id
  • 除非无稳定替代方案,否则避免使用XPath和深层CSS选择器链。
  • 优先使用Web原生断言,避免使用静态等待(
    waitForTimeout
    /
    time.sleep
    )。
  • 测试用例需聚焦:每个测试对应一个核心用户操作目标。
认证模式:
  • 针对大型测试套件,可通过
    storageState
    复用已认证状态(请勿提交至git仓库)。
  • 为不同角色(管理员 vs 普通用户)使用独立的存储状态,避免测试间相互干扰。

Running Tests

运行测试

  • Use headless runs for CI and headed for local debugging.
  • Capture traces/screenshots on failure.
Common commands:
bash
undefined
  • CI环境使用无头模式运行,本地调试使用有头模式。
  • 测试失败时捕获追踪日志/截图。
通用运行命令:
bash
undefined

TS

TS

npx playwright test npx playwright test --ui npx playwright test --debug npx playwright show-trace trace.zip
npx playwright test npx playwright test --ui npx playwright test --debug npx playwright show-trace trace.zip

Python (pytest-playwright)

Python (pytest-playwright)

pytest PWDEBUG=1 pytest -k test_name
undefined
pytest PWDEBUG=1 pytest -k test_name
undefined

Debugging

调试技巧

  • Use
    --debug
    ,
    --trace
    , and
    page.pause()
    .
  • Isolate flaky tests with retries and explicit waits.
  • Use the trace viewer to understand timing and locator failures.
Flakiness triage:
  • Re-run the single test in isolation; if it only fails in-suite, suspect shared state.
  • Ensure assertions are waiting on the right UI signal (URL change, role-visible element, network idle as needed).
  • Prefer fixing root cause over increasing timeouts/retries.
  • 使用
    --debug
    --trace
    参数及
    page.pause()
    方法。
  • 通过重试与显式等待隔离不稳定测试用例。
  • 使用追踪查看器分析时序问题与选择器失败原因。
不稳定用例排查:
  • 单独运行该测试用例;若仅在套件中失败,需排查共享状态问题。
  • 确保断言等待正确的UI信号(URL变更、角色可见元素、网络空闲等)。
  • 优先修复根本原因,而非单纯增加超时时间/重试次数。

Review Checklist

评审检查清单

  • Selectors are stable and readable.
  • Tests assert user-visible outcomes.
  • Failures provide trace/screenshot evidence.
  • Tests are isolated (no order dependence).
  • CI captures artifacts (HTML report, traces, screenshots) for failures.
  • 选择器稳定且可读性强。
  • 测试用例断言用户可见的结果。
  • 失败时提供追踪日志/截图作为证据。
  • 测试用例相互独立(无执行顺序依赖)。
  • CI环境捕获失败用例的产物(HTML报告、追踪日志、截图)。

References

参考资料

  • references/playwright.md
  • references/playwright.md

Extended Guidance

扩展指南

Use this when test flakiness is high or when scaling test suites.
当测试用例不稳定率较高或需要扩展测试套件时参考。

Test Design Rules

测试设计规则

  • Prefer role-based selectors; avoid brittle CSS paths.
  • Keep one assertion per user-visible outcome.
  • Use fixtures for shared state (auth, seeds, test data).
  • Isolate tests; avoid cross-test dependencies.
  • 优先使用基于角色的选择器;避免脆弱的CSS路径。
  • 每个用户可见结果对应一个断言。
  • 使用fixtures管理共享状态(认证、预填充数据、测试数据)。
  • 测试用例相互独立;避免跨测试依赖。

Flake Reduction Tactics

降低测试不稳定性技巧

  • Wait for stable UI states, not arbitrary timeouts.
  • Use
    expect(...).toBeVisible()
    with retries instead of
    waitForTimeout
    .
  • Remove reliance on animation timing; disable animations in test env.
  • 等待UI状态稳定,而非使用任意超时时间。
  • 优先使用带重试机制的
    expect(...).toBeVisible()
    替代
    waitForTimeout
  • 移除对动画时序的依赖;在测试环境中禁用动画。

CI Tips

CI配置技巧

  • Shard tests by file or tag when suites grow.
  • Collect trace on failure for debug.
  • Keep browser versions pinned in CI for reproducibility.
  • Add an explicit browser install step in CI; Playwright no longer downloads browsers on package install.
  • 当测试套件规模扩大时,按文件或标签分片执行测试。
  • 测试失败时收集追踪日志用于调试。
  • 在CI环境中固定浏览器版本以保证可复现性。
  • 在CI环境中添加显式的浏览器安装步骤;Playwright不再通过包安装自动下载浏览器。

Debug Commands

调试命令

bash
npx playwright test --debug
npx playwright test --trace on
bash
npx playwright test --debug
npx playwright test --trace on

Reference Index

参考索引

  • rg -n "Selectors|getByRole" references/playwright.md
  • rg -n "Fixtures|test.extend" references/playwright.md
  • rg -n "Tracing|debug" references/playwright.md
  • rg -n "Selectors|getByRole" references/playwright.md
  • rg -n "Fixtures|test.extend" references/playwright.md
  • rg -n "Tracing|debug" references/playwright.md

Coverage Checklist

覆盖范围检查清单

  • Auth flows (login, logout, token refresh).
  • Critical paths (checkout, onboarding, settings).
  • Error states (404, 500, empty data).
  • 认证流程(登录、登出、令牌刷新)。
  • 核心业务路径(结账、新用户引导、设置页面)。
  • 错误状态(404、500、空数据场景)。

Reference Index (Expanded)

扩展参考索引

  • rg -n "CI|sharding" references/playwright.md
  • rg -n "CI|sharding" references/playwright.md

Quick Questions (When Stuck)

疑难排查快速问题

  • What is the minimal change that solves the issue?
  • What is the rollback plan?
  • What is the highest-risk assumption?
  • What is the simplest validation step?
  • What is the known-good baseline?
  • What evidence would change the decision?
  • What is the user-visible impact?
  • What is the operational impact?
  • What is the most likely failure mode?
  • What is the fastest safe experiment?
  • 解决该问题的最小改动是什么?
  • 回滚方案是什么?
  • 风险最高的假设是什么?
  • 最简单的验证步骤是什么?
  • 已知的可用基线版本是什么?
  • 哪些证据会改变当前决策?
  • 对用户可见的影响是什么?
  • 对运维的影响是什么?
  • 最可能的失败模式是什么?
  • 最快的安全验证实验是什么?

Reference Index (Extra)

额外参考索引

  • rg -n "Checklist|checklist" references/playwright.md
  • rg -n "Example|examples" references/playwright.md
  • rg -n "Workflow|process" references/playwright.md
  • rg -n "Pitfall|anti-pattern" references/playwright.md
  • rg -n "Testing|validation" references/playwright.md
  • rg -n "Security|risk" references/playwright.md
  • rg -n "Configuration|config" references/playwright.md
  • rg -n "Deployment|operations" references/playwright.md
  • rg -n "Troubleshoot|debug" references/playwright.md
  • rg -n "Performance|latency" references/playwright.md
  • rg -n "Reliability|availability" references/playwright.md
  • rg -n "Monitoring|metrics" references/playwright.md
  • rg -n "Error|failure" references/playwright.md
  • rg -n "Decision|tradeoff" references/playwright.md
  • rg -n "Migration|upgrade" references/playwright.md
  • rg -n "Checklist|checklist" references/playwright.md
  • rg -n "Example|examples" references/playwright.md
  • rg -n "Workflow|process" references/playwright.md
  • rg -n "Pitfall|anti-pattern" references/playwright.md
  • rg -n "Testing|validation" references/playwright.md
  • rg -n "Security|risk" references/playwright.md
  • rg -n "Configuration|config" references/playwright.md
  • rg -n "Deployment|operations" references/playwright.md
  • rg -n "Troubleshoot|debug" references/playwright.md
  • rg -n "Performance|latency" references/playwright.md
  • rg -n "Reliability|availability" references/playwright.md
  • rg -n "Monitoring|metrics" references/playwright.md
  • rg -n "Error|failure" references/playwright.md
  • rg -n "Decision|tradeoff" references/playwright.md
  • rg -n "Migration|upgrade" references/playwright.md