E2E-тесты на Playwright

Пишет стабильные браузерные E2E-тесты на Playwright: пользовательские локаторы, web-first проверки вместо sleep, изолированные данные, трейсы при падении и отладка в headed-режиме. Используйте, когда просят добавить или починить браузерные E2E-тесты.

ТестированиеПак: Тестирование103 строкиe2e-playwright

Установка

Выполните одну команду — она сохранит SKILL.md в папку скиллов агента. Перезапустите агента, и он подхватит скилл сам.

Claude Code — macOS, Linux
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
Codex, Cursor — macOS, Linux
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
Claude Code — Windows PowerShell
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"
Codex, Cursor — Windows PowerShell
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

  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:
npm init playwright@latest
npx playwright install chromium
  1. Find how the app starts for tests. Prefer webServer in 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:

  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:

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

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 · License: CC BY 4.0

Подключить через AnyModel API

Скилл работает на той модели, которую использует агент. Подключите Claude Code, Codex или Cursor к AnyModel и запускайте его на Claude, GPT, Gemini и других моделях по одному ключу — оплата за токены, без подписки.

Ещё из пака Тестирование

Разработка через тесты (TDD)

Ведёт изменение по циклу red, green, refactor: пишет падающий тест с описанием поведения, добавляет минимум кода для прохождения и рефакторит на зелёных тестах. Для фич и багфиксов с тестом вперёд.

Написание юнит-тестов

Пишет точечные юнит-тесты для существующего кода: находит публичное поведение, покрывает крайние случаи и ошибки, делает осмысленные проверки и следует фреймворку и стилю проекта. Для добавления тестов к функции или модулю.

Пробелы в покрытии тестами

Находит рискованный непокрытый код: запускает coverage, ранжирует пробелы по риску (деньги, авторизация, потеря данных, парсинг), а не по проценту, и предлагает несколько самых важных тестов. Используйте, когда спрашивают, где не хватает тестов, или просят поднять покрытие.

Контрактные тесты API

Пишет тесты HTTP API: коды ответов, схемы, формат ошибок, авторизация и права, идемпотентность, пагинация, без зависимости от состояния базы. Для тестирования REST и JSON API.