---
name: e2e-playwright
description: Writes stable browser end-to-end tests with Playwright using user-facing locators, web-first assertions instead of sleeps, isolated test data, traces on failure and headed debugging. Use when asked to add or fix browser E2E tests.
---

# Playwright End-to-End Tests

An E2E test drives the app like a user. It is slow and fragile compared with unit tests, so write few of them, aimed at critical user journeys, and make each one stable.

## Setup check

1. Look for an existing `playwright.config.ts` (or `.js`) and the `tests/` or `e2e/` folder. Follow its conventions: base URL, projects (browsers), test directory, fixtures, page objects.
2. If Playwright is not installed, ask the user before adding a dependency. Then:

```sh
npm init playwright@latest
npx playwright install chromium
```

3. Find how the app starts for tests. Prefer `webServer` in the config so the test run starts the app itself:

```ts
webServer: { command: 'npm run dev', url: 'http://localhost:3000', reuseExistingServer: !process.env.CI },
use: { baseURL: 'http://localhost:3000', trace: 'retain-on-failure', screenshot: 'only-on-failure' },
```

## Writing a test

### Pick the journey

Choose what must never break: sign up and log in, checkout, creating and editing the main resource, permissions. One test per journey, with a name stating the outcome: `user can add an item to the cart and pay`.

### Locators: what the user sees

Prefer, in this order:

1. `page.getByRole('button', { name: 'Save' })`
2. `page.getByLabel('Email')`, `getByPlaceholder`, `getByText`
3. `page.getByTestId('order-row')` when no accessible name exists (add `data-testid` to the app, tell the user).

Avoid CSS chains and XPath such as `div > div:nth-child(3) .btn`; they break on layout changes. If `getByRole` cannot find an element, that can be an accessibility bug; mention it.

### Assertions: web-first, never sleeps

Use auto-waiting assertions, which retry until the condition holds or times out:

```ts
await expect(page.getByRole('heading', { name: 'Order confirmed' })).toBeVisible();
await expect(page).toHaveURL(/\/orders\/\d+/);
await expect(page.getByTestId('cart-count')).toHaveText('2');
```

- Do not use `page.waitForTimeout(…)` or `sleep`. Wait for the thing you need: a locator state, a URL, or a specific response with `page.waitForResponse`.
- Do not assert on a snapshot of `await locator.textContent()` immediately; use `expect(locator).toHaveText`.
- Actions (`click`, `fill`) already wait for the element to be actionable.

### Isolated data

- Each test creates its own data (a unique user such as `user-${Date.now()}@example.test`, a fresh order) via the API or a seeding helper, not through a long UI flow.
- Do not rely on data left by another test, and do not depend on test order. Tests must pass when run alone, in parallel, and repeated.
- Log in once through API or `storageState` and reuse it, instead of logging in through the form in every test. Keep the state file out of git; it contains session cookies.
- Never use real accounts, real payment cards or production URLs. Use test credentials from environment variables, never hard-coded in the repo.
- Stub third-party services you do not control with `page.route(…)` to keep the run deterministic.

### Structure

- Use `test.beforeEach` for common navigation, `test.step` to label phases in the report.
- Repeated flows go into a small helper or page object. Do not build a large abstraction for two tests.
- Keep each test short: about 10 to 20 lines of actions and assertions.

## Debugging and running

```sh
npx playwright test                         # headless, all projects
npx playwright test tests/cart.spec.ts      # one file
npx playwright test -g "add an item"        # by title
npx playwright test --headed                # watch the browser
npx playwright test --debug                 # step through with the inspector
npx playwright test --ui                    # UI mode with time travel
npx playwright show-trace test-results/<run>/trace.zip
npx playwright show-report
npx playwright test --repeat-each=20        # flakiness check
```

Traces show every action, DOM snapshot, network call and console message; open the trace before guessing at a failure.

## Report format

- Journeys covered and files added.
- Command to run them and the result (passed, failed, flaky counts, repeat count).
- Selectors or `data-testid` attributes you added to the app.
- Known gaps (not covered browsers, payment in sandbox only).

## Pitfalls

- Sleeps and retries to hide timing problems; find the real condition to wait for.
- Tests sharing one account or one database record, which breaks in parallel runs.
- Asserting on text that changes (dates, counters, random names) without controlling it.
- Committing traces, videos, `storageState` files or screenshots that contain personal data.
- Running destructive flows (delete account, send real emails) against a shared or production environment. Ask the user which environment to use.
- Treating a green run as proof; run with `--repeat-each` before calling a new test stable.

Source: [AnyModel skills catalog](https://anymodel.org/en/skills) · License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
