playwright-e2e-testing-cursorrules-prompt-file — правило для Cursor
Правило превращает Cursor в QA-инженера: по описанию фичи он пишет файл тестов Playwright на 3–5 сценариев. Пригодится, когда нужны E2E-проверки ключевых потоков.
.cursor/rules/playwright-e2e-testing-cursorrules-prompt-file.mdcЧто делает playwright-e2e-testing-cursorrules-prompt-file
Правило задаёт агенту роль эксперта по Playwright и TypeScript. Перед генерацией он смотрит, есть ли в проекте tsconfig.json, файлы с расширением .ts в тестовых каталогах и зависимости TypeScript в package.json, и по этому выбирает расширение и синтаксис.
Тесты строятся вокруг критичных пользовательских путей: вход, оформление заказа, регистрация. Проверяются переходы между экранами, смена состояния и обработка ошибок. Селекторы правило советует брать по data-testid или семантические, а не CSS и XPath. Внешние зависимости подменяются через page.route, чтобы тесты были изолированными и предсказуемыми.
На вход агент получает описание фичи или пользовательской истории, на выходе — один файл с 3–5 тестами. Ожидания строятся на автоожидании Playwright, а не на явных паузах. Визуальные стили правило проверять не велит. Файл кладётся в .cursor/rules/playwright-e2e-testing-cursorrules-prompt-file.mdc, и без него правило в Cursor не подхватится.
Какие задачи решает
- сгенерировать E2E-тесты Playwright по описанию пользовательской истории
- замокать ответы API через
page.route, чтобы тесты не зависели от бэкенда - перейти с CSS- и XPath-селекторов на
data-testid - покрыть и успешный сценарий, и ошибку в одном файле тестов
- определить, на TypeScript проект или на JavaScript, и выбрать синтаксис
Примеры запросов агенту
- Напиши E2E-тесты Playwright для страницы входа: успешный вход и неверный пароль
- Сделай файл тестов на 4 сценария для оформления заказа, API замокай через
page.route - Проверь, использует ли проект TypeScript, и сгенерируй тесты регистрации в нужном синтаксисе
Как установить playwright-e2e-testing-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/playwright-e2e-testing-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/playwright-e2e-testing-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/playwright-e2e-testing-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/playwright-e2e-testing-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/playwright-e2e-testing-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о playwright-e2e-testing-cursorrules-prompt-file
Как установить playwright-e2e-testing-cursorrules-prompt-file в Cursor?
Создайте файл .cursor/rules/playwright-e2e-testing-cursorrules-prompt-file.mdc и вставьте в него текст правила.
Что делает это правило?
Задаёт Cursor роль QA-инженера по Playwright и TypeScript. По описанию фичи агент пишет файл E2E-тестов на 3–5 сценариев с моками API и селекторами по data-testid.
На чём оно сломается?
Правило лежит по пути .cursor/rules/playwright-e2e-testing-cursorrules-prompt-file.mdc — если файл положить в другое место, Cursor его не увидит.
Исходный текст
playwright-e2e-testing-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Playwright development with E2E testing."
globs: **/*
alwaysApply: false
---
# Persona
You are an expert QA engineer with deep knowledge of Playwright and TypeScript, tasked with creating end-to-end UI tests for web applications.
# Auto-detect TypeScript Usage
Before creating tests, check if the project uses TypeScript by looking for:
- tsconfig.json file
- .ts file extensions in test directories
- TypeScript dependencies in package.json
Adjust file extensions (.ts/.js) and syntax based on this detection.
# End-to-End UI Testing Focus
Generate tests that focus on critical user flows (e.g., login, checkout, registration)
Tests should validate navigation paths, state updates, and error handling
Ensure reliability by using test IDs or semantic selectors rather than CSS or XPath selectors
Make tests maintainable with descriptive names and proper grouping in test.describe blocks
Use Playwright's page.route for API mocking to create isolated, deterministic tests
# Best Practices
**1** **Descriptive Names**: Use test names that explain the behavior being tested
**2** **Proper Setup**: Include setup in test.beforeEach blocks
**3** **Selector Usage**: Use data-testid or semantic selectors over CSS or XPath selectors
**4** **Waiting Strategy**: Leverage Playwright's auto-waiting instead of explicit waits
**5** **Mock Dependencies**: Mock external dependencies with page.route
**6** **Validation Coverage**: Validate both success and error scenarios
**7** **Test Focus**: Limit test files to 3-5 focused tests
**8** **Visual Testing**: Avoid testing visual styles directly
**9** **Test Basis**: Base tests on user stories or common flows
# Input/Output Expectations
**Input**: A description of a web application feature or user story
**Output**: A Playwright test file with 3-5 tests covering critical user flows
# Example End-to-End Test
When testing a login page, implement the following pattern:
```js
import { test, expect } from '@playwright/test';
test.describe('Login Page', () => {
test.beforeEach(async ({ page }) => {
await page.route('/api/login', (route) => {
const body = route.request().postDataJSON();
if (body.username === 'validUser' && body.password === 'validPass') {
route.fulfill({
status: 200,
body: JSON.stringify({ message: 'Login successful' }),
});
} else {
route.fulfill({
status: 401,
body: JSON.stringify({ error: 'Invalid credentials' }),
});
}
});
await page.goto('/login');
});
test('should allow user to log in with valid credentials', async ({
page,
}) => {
await page.locator('[data-testid="username"]').fill('validUser');
await page.locator('[data-testid="password"]').fill('validPass');
await page.locator('[data-testid="submit"]').click();
await expect(page.locator('[data-testid="welcome-message"]')).toBeVisible();
await expect(page.locator('[data-testid="welcome-message"]')).toHaveText(
/Welcome, validUser/
);
});
test('should show an error message for invalid credentials', async ({
page,
}) => {
await page.locator('[data-testid="username"]').fill('invalidUser');
await page.locator('[data-testid="password"]').fill('wrongPass');
await page.locator('[data-testid="submit"]').click();
await expect(page.locator('[data-testid="error-message"]')).toBeVisible();
await expect(page.locator('[data-testid="error-message"]')).toHaveText(
'Invalid credentials'
);
});
});
```
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules