Use when writing E2E web tests, debugging flaky tests, or setting up Playwright CI. Covers: stable selectors (getByRole), parallelization/sharding, flake control, network mocking, visual testing, MCP/AI automation, and CI/CD integration.
High-signal, cost-aware E2E testing for web applications.
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 (High ROI) |
| Decide tool fit, selectors, flake triage order, sharding cost | ## Expert Judgment |
| Load templates and references | ## Navigation |
getByRole → getByLabel/getByText → getByTestId (fallback).webServer), then triage with an exact spec or named batch plus --workers=1.failOnFlakyTests; use a custom reporter only for older Playwright versions.references/playwright-mcp.md.@playwright/cli (shell commands) over Playwright MCP — roughly 4x fewer tokens per task (~27k vs ~114k tokens/task per third-party benchmarks; as of 2026-07-11, verify at https://playwright.dev/docs/getting-started-cli). Use 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 |
| 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 <trace.zip> | Analyze trace from CLI (v1.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.--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 | Storybook + Chromatic/Percy, or Playwright component testing only if you accept experimental-API churn (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:
retries to gather evidence (trace/video) on the first CI run, but treat "passed on retry" as an unresolved defect, not a pass. See template-playwright-fail-on-flaky-reporter.js.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.Make tests independent and deterministic
Use network mocking for third-party deps
Run smoke E2E on PRs; full regression on schedule
"Test everything E2E" as default
Weakening assertions to "fix" flakes
Auto-healing that weakens assertions
Run this preflight before expensive E2E runs to prevent avoidable failures.
rg --files tests/e2e | rg <target>).lsof -i :3001).webServer.--no-server during local deflake work.--grep over broad globs during triage.test -f <error-context.md>).test-results index first.Before running Playwright in constrained environments (sandboxed terminals, CI containers, shared dev hosts), decide and document:
127.0.0.1 or 0.0.0.0, and verify selected port is free.webServer; never run both accidentally.EPERM/EACCES, escalate immediately instead of retry loops..next/lock and terminate stale build/dev PIDs before rerun.--workers=1 on the chosen server topology.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.EADDRINUSE on Playwright web server port| 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 strategies | | references/api-testing-playwright.md | API testing with APIRequestContext | | 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 | Fail CI on rerun-pass flakes | | assets/template-playwright-preflight-checklist.md | Preflight checklist for port/sandbox/timeouts |
Playwright testing request
-> Confirm app root, server topology, ports, auth state, and target spec
-> Author the smallest user-outcome test with semantic locators
-> Isolate fixtures, storage, network, third parties, and worker state
-> Reproduce with one spec or grep and workers=1 before widening
-> Debug using trace, screenshots, video, console, and network evidence
-> Gate PR or deploy only after flakes are classified and fixed
## Workflow, ## Debugging Checklist, and ## Execution Preflight (High ROI) for the baseline sequence## Expert Judgment for tool-fit, selector, flake-triage-order, and CI-sharding-economics decision rules## Resources and ## Templates for deeper materials## Related Skills for strategy, frontend, and CI handoffs| Skill | Purpose | |-------|---------| | qa-testing-strategy | Overall test strategy | | software-frontend | Frontend development | | ops-devops-platform | CI/CD integration |
Before delivering output, you MUST verify:
Before applying this skill on a non-trivial task, read learnings.consolidated.md in this directory (and learnings.md if present).
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.
npx skills add vasilyu1983/qa-testing-playwright下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer