协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
qa-testing-playwright【开发与工程】Builds and debugs Playwright E2E suites. Use when authoring browser tests, fixing flakes, or hardening Playwright CI and locator strategy.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Core docs:
| Need | Go to |
|---|---|
| Run the Playwright workflow | ## Workflow |
| Apply defaults and authoring rules | ## Defaults and ## Authoring Rules |
| Debug flaky or blocked runs | ## Debugging Checklist and ## Execution Preflight |
| Decide tool fit, selectors, flake triage order, sharding cost | ## Expert Judgment |
| Load templates and references | ## Resources and ## Templates |
getByRole → getByLabel/getByText → getByTestId (fallback).test(title, { lock: 'user-settings' }, fn)) instead of workers: 1 or describe.serial for the whole file.webServer), then triage with an exact spec or named batch plus --workers=1.failOnFlakyTests (1.52+); the custom reporter template is legacy, for pre-1.52 pins only.mount('components/X/Story') fixture from @playwright/test (1.62+). The @playwright/experimental-ct-* packages were frozen in 1.63 and the docs now say they are removed; stay on 1.62 until migrated. See references/playwright-patterns.md#component-testing.toHaveScreenshot when one OS/browser baseline set in Docker is enough; a hosted service when designers review diffs or the browser/OS matrix makes committed baselines unmanageable. See references/visual-regression-testing.md.references/playwright-mcp.md.npx playwright cli; shell commands) over Playwright MCP — it avoids the MCP protocol's per-call token overhead. Check npx playwright cli --version / release notes for your installed version before relying on it, since CLI availability and flags vary by release. The official docs call it token-efficient without a number; treat any specific token-count figure (e.g. a "tokens/task" comparison) as a claim to verify against your own measurement, not a quotable fact. Use MCP (npx playwright mcp) when persistent browser state and rich introspection are needed.npx playwright test --only-changed=main to run only tests affected by uncommitted/branch changes during authoring; it is a heuristic over the import graph, so always run the full suite (or the deploy-gate replay) before merging — never treat --only-changed green as release-ready signal.| Command | Purpose |
|---|---|
npm init playwright@latest | Initialize Playwright |
npx playwright test | Run all tests |
npx playwright test --grep @smoke | Run smoke tests |
npx playwright test --project=chromium | Run a single project |
npx playwright test --ui | Debug with UI mode |
npx playwright test --debug | Step through a test |
npx playwright codegen | Record a flow and bootstrap a test |
npx playwright init-agents --loop=claude | Initialize test agents for Claude Code (--loop=codex, vscode, opencode also exist) |
npx playwright test --debug=cli | Let a coding agent attach and debug a test via playwright-cli (1.59+) |
npx playwright test --last-failed | Rerun only the tests that failed in the last run |
npx playwright test --fail-on-flaky-tests | Fail CI if any test is flaky |
npx playwright show-trace trace.zip | Inspect trace artifacts |
npx playwright show-report | Inspect HTML report |
npx playwright trace open <trace.zip> | Open a trace for CLI analysis; then trace actions, trace action <n>, trace snapshot <n> --name after, trace close (1.59+) |
npx playwright test --only-changed=main | Run only tests affected by changes since main (heuristic — always follow with a full run before release) |
Use this order by default:
--no-server over spawning a fresh app per rerun.runtime observed, build identity unverified.--workers=1.Default suite tiers:
Avoid local full-suite reruns as the first move unless the job is explicitly “prove deploy readiness now.”
| Scenario | Use Instead |
|---|---|
| Unit testing | Jest, Vitest, pytest |
| API contracts | qa-api-testing-contracts |
| Load testing | k6, Locust, Artillery |
| Mobile native | Appium |
| Pure business-logic or data-transform correctness | Unit tests — a browser adds latency and flake with zero extra confidence |
| Cross-team API contract drift | Consumer-driven contract tests, not a UI click-path proxy |
| Component-level visual/interaction isolation at scale | Playwright stories/gallery component tests (1.62+, stable) if you already run Playwright; Storybook + Chromatic/Percy if the team reviews visual diffs in a hosted UI (see Defaults) |
| Thousands of input-combination fuzzing | Property-based testing at the unit layer; E2E cannot afford the runtime |
Playwright (or any browser E2E tool) is the wrong choice when a faster, cheaper layer already proves the same risk:
request fixture or a dedicated API-testing skill) and skip the browser.Pick the locator in this order, and stop at the first one that resolves unambiguously to exactly one element:
getByRole with an accessible name — this is what a screen reader and a real user both key off, so it survives markup refactors.getByLabel / getByText — use when there is no meaningful role (plain text, decorative containers) but the visible copy is stable.getByTestId — use only when the element has no stable role/label (e.g., a canvas, a drag handle, a duplicate-name list item) or when semantic locators would force asserting on implementation detail (raw CSS class, generated ID).
Never fall back to raw CSS or XPath as a first resort — they are a signal that the markup itself may need an accessibility fix, not just a test workaround.Before touching a single assertion, classify the failure in this order — each step is strictly cheaper than the next, so do not skip ahead:
lock on exactly the tests that touch it (1.63+) rather than serializing the suite.auth-state, state-sync, optional-network, and degraded-mode (see ### Stateful App Failure Classes) before assuming a product bug.retries to gather evidence (trace/video) on the first CI run, but treat "passed on retry" as an unresolved defect, not a pass (failOnFlakyTests: true).Flake forensics tooling (check availability against your pinned version):
retryStrategy: 'isolated' (1.62+) runs all retries at the end, one by one in a single worker. A test that fails in-suite but passes isolated points to interference (step 3); one that still fails isolated points to steps 1, 2 or 6.trace: 'retain-on-failure-and-retries' (1.59+; a video mode since 1.61) keeps both the failing and the passing attempt, so you can diff them side by side.--repeat-each=N on the single suspect test proves a fix; --last-failed reruns only the previous failures.@flaky with an owner and an exit date, and exclude it from the gate with --grep-invert @flaky or a Reporter.preprocess() skip list (1.62+). A quarantined test with no owner is a deleted test.Sharding trades machine-cost for wall-clock time; the math to decide is straightforward. Given a suite that takes T minutes single-threaded and N shards each with M machine-minutes of fixed overhead (checkout, install, browser download):
T/N + M.N × (T/N + M) = T + N×M.Example: T = 60 min, M = 3 min fixed overhead per shard/job.
Sharding always costs more total machine-minutes (because fixed overhead is paid N times) — the return is faster PR feedback, not lower spend. The judgment call: shard the PR-gate smoke suite (wall-clock matters, suite is small so N×M stays small) and run the full regression unsharded or lightly sharded on a schedule (spend matters more than latency there). Re-derive this ratio with your own T and M before picking a shard count — do not copy N=4 by convention.
// 1. Role locators (preferred)
await page.getByRole('button', { name: 'Sign in' }).click();
// 2. Label/text locators
await page.getByLabel('Email').fill('user@example.com');
// 3. Test IDs (fallback)
await page.getByTestId('user-avatar').click();
failOnFlakyTests in CIforce: truewebServer, plus exact start/stop commands.If something is flaky:
auth-state before changing assertions.429 or Retry-After on side endpoints, decide whether that request is part of the oracle or only noise.expect(...), an auth-aware navigation helper, or a targeted readiness assertion.test.step(name, fn, { timeout }) over raising timeout in playwright.config.ts.Before expensive E2E runs, run the preflight in references/playwright-preflight-sandbox.md (spec paths, port/host binding, one server topology, build locks, per-test timeout budget, EPERM/EACCES escalation) and record the answers with assets/template-playwright-preflight-checklist.md. Treat EADDRINUSE, missing spec/result paths and shell-glob failures on bracketed route segments as environment failures, not product bugs.
auth-state: protected route unexpectedly redirects to login or loses storage/session state.state-sync: backend reset or webhook succeeded, but UI has not converged yet.optional-network: a side request failed, but the user-visible oracle may still be correct.degraded-mode: rate limits or fallback UX activated and should be asserted intentionally.| Resource | Purpose |
|---|---|
| references/playwright-mcp.md | MCP & AI testing |
| references/playwright-patterns.md | Advanced patterns |
| references/playwright-ci.md | CI configurations |
| references/playwright-authentication.md | Auth patterns and session management |
| references/visual-regression-testing.md | Visual regression (library canonical): native vs hosted, baselines, thresholds |
| references/api-testing-playwright.md | request fixture for UI+API hybrid tests (contract/schema work lives in qa-api-testing-contracts) |
| references/playwright-preflight-sandbox.md | Sandbox/port preflight and escalation decisions |
| data/sources.json | Documentation links |
| Template | Purpose |
|---|---|
| assets/template-playwright-e2e-review-checklist.md | E2E review checklist |
| assets/template-playwright-fail-on-flaky-reporter.js | Legacy: fail CI on rerun-pass flakes for Playwright < 1.52 only; use failOnFlakyTests otherwise |
| assets/test-fail-on-flaky-reporter.test.js | node --test checks for the legacy flaky reporter |
| assets/template-playwright-preflight-checklist.md | Preflight checklist for port/sandbox/timeouts |
Use Quick Reference to select the workflow, debugging path, or resource.
| Skill | Purpose |
|---|---|
| qa-testing-strategy | Overall test strategy |
| software-frontend | Frontend development |
| ops-devops-platform | CI/CD integration |
Before delivering, check:
When prior decisions or pitfalls are relevant, consult learnings.consolidated.md if present; use learnings.md only for needed history or as the available fallback. Otherwise skip both.
After applying it, if you encountered a pattern worth remembering, a mistake worth preventing, or a domain fact that surprised you, append one dated bullet to learnings.md via agents-skills-feedback-loop/scripts/append_learning.py. Do not modify SKILL.md itself.