E2E-тесты на Playwright
Пишет стабильные браузерные E2E-тесты на Playwright: пользовательские локаторы, web-first проверки вместо sleep, изолированные данные, трейсы при падении и отладка в headed-режиме. Используйте, когда просят добавить или починить браузерные E2E-тесты.
e2e-playwrightУстановка
Выполните одну команду — она сохранит SKILL.md в папку скиллов агента. Перезапустите агента, и он подхватит скилл сам.
mkdir -p ~/.claude/skills/e2e-playwright && curl -fsSL https://anymodel.org/en/skills/testing/e2e-playwright/SKILL.md -o ~/.claude/skills/e2e-playwright/SKILL.md
mkdir -p ~/.agents/skills/e2e-playwright && curl -fsSL https://anymodel.org/en/skills/testing/e2e-playwright/SKILL.md -o ~/.agents/skills/e2e-playwright/SKILL.md
New-Item -ItemType Directory -Force "$HOME\.claude\skills\e2e-playwright" | Out-Null; Invoke-WebRequest https://anymodel.org/en/skills/testing/e2e-playwright/SKILL.md -UseBasicParsing -OutFile "$HOME\.claude\skills\e2e-playwright\SKILL.md"
New-Item -ItemType Directory -Force "$HOME\.agents\skills\e2e-playwright" | Out-Null; Invoke-WebRequest https://anymodel.org/en/skills/testing/e2e-playwright/SKILL.md -UseBasicParsing -OutFile "$HOME\.agents\skills\e2e-playwright\SKILL.md"
Другой агент: сохраните файл в его папку скиллов или дайте ему ссылку на файл: https://anymodel.org/en/skills/testing/e2e-playwright/SKILL.md
SKILL.md
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
- Look for an existing
playwright.config.ts(or.js) and thetests/ore2e/folder. Follow its conventions: base URL, projects (browsers), test directory, fixtures, page objects. - If Playwright is not installed, ask the user before adding a dependency. Then:
npm init playwright@latest
npx playwright install chromium
- Find how the app starts for tests. Prefer
webServerin the config so the test run starts the app itself:
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:
page.getByRole('button', { name: 'Save' })page.getByLabel('Email'),getByPlaceholder,getByTextpage.getByTestId('order-row')when no accessible name exists (adddata-testidto 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:
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(…)orsleep. Wait for the thing you need: a locator state, a URL, or a specific response withpage.waitForResponse. - Do not assert on a snapshot of
await locator.textContent()immediately; useexpect(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
storageStateand 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.beforeEachfor common navigation,test.stepto 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
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-testidattributes 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,
storageStatefiles 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-eachbefore calling a new test stable.
Source: AnyModel skills catalog · License: CC BY 4.0
Подключить через AnyModel API
Скилл работает на той модели, которую использует агент. Подключите Claude Code, Codex или Cursor к AnyModel и запускайте его на Claude, GPT, Gemini и других моделях по одному ключу — оплата за токены, без подписки.
AnyModel