/playwright-automation:write-test-codefrom playwright-automation
This skill should be used when writing, refactoring, or modifying Playwright E2E test code. It covers creating test files from TC-ID specs, converting browser exploration results to executable tests, refactoring locators or fixtures, adding API mocking, test data setup/teardown, and parallel-safe isolation. Includes locator strategy hierarchy, auth setup patterns, fixture design, teardown strategies, and network interception recipes. Triggers: "write a test for", "add a test case", "refactor this locator", "add error path tests", "convert specs to code", "add API mocking", "set up auth for tests". NOT for: full pipeline from scratch (use add-playwright-tests), shared live-site exploration (use capture-feature-evidence), generating specs without code (use plan-test-coverage or generate-test-cases), diagnosing flaky tests (use fix-flaky-tests).
Ships in playwright-automation. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Write, refactor, or fix Playwright E2E tests. Convert browser exploration results or test case specifications into executable, stable test code.
Parse the test description or spec file path from: $ARGUMENTS
playwright.config.ts / playwright.config.js — extract baseURL, testDir, projectsdocs/qa/exploration-report.md when selector evidence or observed flow behavior matterscapture-feature-evidence to produce or refresh docs/qa/exploration-report.md before writing code — do not guesspage.waitForResponse for critical checkpointsnpx playwright test <file> --reporter=list 2>&1--headed — it will fail silently or hang--headed only during local interactive debugging when you need to visually observe the testReturn:
Assert what appears on the page — visible text, URL changes, enabled/disabled states — not internal state, CSS classes, or component hierarchy.
Avoid page.waitForTimeout() except as a last-resort debug aid — remove before finishing.
| Priority | Method | When to Use |
|---|---|---|
| 1 | getByRole('role', { name }) | Buttons, links, headings, form controls |
| 2 | getByLabel() | Form fields with visible labels |
| 3 | getByPlaceholder() | Inputs with placeholder text |
| 4 | getByTestId() | When data-testid is available |
| 5 | getByText() | Short, stable text (avoid marketing copy) |
| 6 | CSS selectors | Last resort, always scoped tightly |
Avoid .first() / .nth() unless a strong, documented reason exists — scope locators to a container instead.
Within-file consistency: Every test file must use ONE locator approach for equivalent elements. Do not mix getByPlaceholder('Email') in one test with page.locator('input[placeholder="Email"]') in another test within the same file. When adding tests to an existing file, match the locator style already in use. If the existing style is suboptimal, refactor all locators in the file together — do not create inconsistency.
expect(...) assertionsTC-<FEATURE>-<NNN>test('TC-LOGIN-001: User can log in with valid credentials', ...)pages/ directory or BasePage class, ALL new tests MUST use Page Objects for interactionsfullyParallel: true is configured, tests run concurrently across workers. A test that creates a record (e.g., a ticket) and then asserts it appears in a list WILL race with other tests creating records. Solutions: (a) assert on the specific record you created (filter/search by the unique ID from your API setup), not on list position or count; (b) use test.describe.serial for flows that genuinely require sequence (create-then-verify); (c) scope list assertions with .filter({ hasText: uniqueIdentifier }) to avoid seeing other workers' data.expect matchers (auto-retry, better error messages)isVisible() + expect(true) patternbaseURL and relative navigation (page.goto('/'))trace: 'on-first-retry', screenshot: 'only-on-failure', video: 'on-first-retry' for CI debuggingretries: process.env.CI ? 2 : 0 — retries in CI onlynpx playwright show-trace trace.zip to time-travel through failurestsconfig.json defines path aliases (e.g., @pages/*, @fixtures/*, @utils/*), use them in imports instead of relative paths. Check tsconfig paths before writing any import statement.Use storageState for most projects (log in once in global setup, reuse across tests).
For parallel workers needing separate accounts, use worker-scoped fixtures.
For multi-role tests (admin + user), create separate browser contexts.
Per-test login is only for testing the login flow itself.
Never hardcode tokens — use environment variables or .env.test.
See references/auth-patterns.md for full patterns with code examples.
Use API calls (not UI clicks) to seed test data — 10-50x faster and more reliable.
Use UI setup only when the creation flow IS the test. Tests that create persistent data
MUST clean up: use afterEach API deletion, fixture-with-cleanup, or bulk globalTeardown.
If no cleanup endpoint exists, document the gap with a TODO.
See references/api-setup-teardown.md for full patterns with code examples.
Use page.route() to mock server errors, patch responses, assert backend calls, or block
heavy resources. Add error path tests when they meaningfully apply to the feature: for example,
server/network failures for backend-driven flows, empty states for collection/data-driven UIs,
and session/auth cases for gated features. If a category is not applicable, do not invent it.
See references/network-interception.md for full patterns with code examples.
Use test.extend to create reusable test setup without duplicating code:
// fixtures/index.ts
import { test as base, Page } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
export const test = base.extend<{
loginPage: LoginPage;
authenticatedPage: Page;
}>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
authenticatedPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'tests/.auth/user.json'
});
const page = await context.newPage();
await use(page);
await context.close();
},
});
export { expect } from '@playwright/test';
Import test from your fixtures file, not from @playwright/test, in test files that need custom fixtures.
When converting journey specs or exploration results to code, consult the mapping tables for standard translations of scopes, actions, assertions, and target kinds to Playwright API calls. For low-confidence journey steps (<0.7), add extra assertions and include fallback locators as comments.
See references/mapping-tables.md for the full tables.
// If the project has custom fixtures (fixtures/index.ts), import from there:
// import { test, expect } from '@fixtures/index';
// Otherwise, use the default:
import { test, expect } from '@playwright/test';
test('TC-FEATURE-001: Description of test case', async ({ page }) => {
// Arrange
await page.goto('/feature-path');
// Act
await page.getByRole('button', { name: /submit/i }).click();
// Assert
await expect(page.getByText(/success/i)).toBeVisible();
});
Always check for a project fixtures file before using the default import. If custom fixtures exist, you MUST import from them to get access to page objects and custom setup.
waitForTimeout() — use proper assertions/waits.nth() / .first() — scope to containerexpect(await el.isVisible()).toBe(true) — use await expect(el).toBeVisible(){ force: true } — diagnose root cause insteadnetworkidle as default wait — use specific response waitsSee references/anti-patterns.md for detailed explanations and fix strategies.
agents/claude.yaml (opens in a new tab)agents/openai.yaml (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/api-setup-teardown.md (opens in a new tab)references/auth-patterns.md (opens in a new tab)references/mapping-tables.md (opens in a new tab)references/network-interception.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub lespaceman/athena-workflow-marketplace --plugin playwright-automation5 skills in this plugin
/add-playwright-testsTHE DEFAULT ENTRY POINT for the Playwright execution layer in the split testing suite. Use to add, create, or set up Playwright end-to-end tests for a feature, page, or application. It orchestrates the full Playwright workflow after shared exploration and planning: analyze the Playwright codebase, consume `docs/qa/feature-map.md`, `docs/qa/exploration-report.md`, `docs/qa/coverage-plan.md`, and `docs/qa/test-cases/*.md`, write production-grade test code, review it, and verify it with real execution. Delegates to `analyze-test-codebase`, `write-test-code`, `review-test-code`, and `fix-flaky-tests`, while relying on shared `map-feature-scope`, `capture-feature-evidence`, `plan-test-coverage`, `generate-test-cases`, and `review-test-cases`.
/analyze-test-codebaseScans and reports on an existing Playwright test codebase. This skill should be used to inspect the current Playwright setup before writing, reviewing, or fixing tests, and should be loaded early when working in a new project to understand existing patterns. Covers: Playwright config, page objects, fixtures, helpers, auth/globalSetup patterns, test conventions, and directory structure. Triggers: "understand", "check", "show me", "inspect", or "analyze" the current test setup, config, infrastructure, patterns, or conventions. In the full add-tests workflow, this skill serves as an early read-only analysis sub-step before planning detailed coverage or writing code. This skill examines existing files and outputs a structured report. It does NOT write or fix tests, install Playwright, or explore live websites — for live-site exploration, use `capture-feature-evidence` so evidence is captured in `docs/qa/exploration-report.md`.
/fix-flaky-testsThis skill should be used when a Playwright test is failing, flaky, timing out, or behaving inconsistently. It provides structured root cause analysis for: stabilizing intermittent tests, debugging timeouts ("Test timeout of 30000ms exceeded"), fixing race conditions, investigating local-vs-CI divergence, running repeated stability checks (--repeat-each). IMPORTANT: If running tests with --repeat-each, --retries, or multiple times to check stability, STOP and load this skill first — it has structured root cause analysis that prevents brute-force approaches. Triggers: "stabilize", "intermittent", "flaky", "keeps failing", "fails in CI", "timeout on", "race condition", "run N times to check stability", "verify tests are stable". NOT for writing new tests (use write-test-code) or analyzing setup (use analyze-test-codebase).
/review-test-codeQuality review of Playwright test code before final execution signoff. This skill should be used when implementation review of executable Playwright tests is needed, not for diagnosis of runtime flakiness. Triggers: "review test code", "review Playwright tests", "check test quality", "audit test implementation", "review my tests before merging", "check test code for issues", "review e2e tests", "code review Playwright", "are my tests stable", "check for brittle selectors", "review before running tests". Quality gate after write-test-code — catches brittle selectors, force:true misuse, networkidle overuse, Tailwind utility class selectors, exact numeric assertions, missing teardown, parallel-unsafe mutations, hardcoded data, missing assertions, test coupling, and convention divergence. Review-only — does NOT rewrite tests, does NOT run tests. Use fix-flaky-tests for fixing, write-test-code for rewriting.