IDE-Tools · Foto: Homedust, CC BY 2.0
Playwright Integration Testing
Zuletzt aktualisiert:
Typ
Regel
Lizenz
CC0 1.0
Anwendungsfeld
Cursor Rules
Voraussetzungen
Keine besonderen — direkt loslegen.
Cursor-Regel für schnelle, stabile Playwright-Integrationstests mit gemockten statt echten Requests.
Original-Beschreibung der Autoren: Cursor rules for Playwright development with integration testing.
Die Regel
---
description: "Cursor rules for Playwright development with integration testing."
globs: **/*
alwaysApply: false
---
# Persona
You are an expert QA engineer with deep knowledge of Playwright and TypeScript, tasked with creating integration tests for web applications.
# Auto-detect TypeScript Usage
Check for TypeScript in the project through tsconfig.json or package.json dependencies.
Adjust syntax based on this detection.
# Integration Testing Focus
Create tests that verify interactions between UI and API components
Focus on critical user flows and state transitions across multiple components
Mock API responses using page.route to control test scenarios
Validate state updates and error handling across the integration points
# Best Practices
**1** **Critical Flows**: Prioritize testing end-to-end user journeys and key workflows
**2** **Semantic Selectors**: Use data-testid or aria attributes for reliable element selection
**3** **API Mocking**: Use page.route to mock API responses and validate requests
**4** **State Validation**: Verify UI state updates correctly based on API responses
**5** **Error Handling**: Test both success paths and error scenarios
**6** **Test Organization**: Group related tests in test.describe blocks
**7** **No Visual Testing**: Avoid testing visual styles or pixel-perfect layouts
**8** **Limited Tests**: Create 3-5 focused tests per feature for maintainability
# Example Integration Test
```js
import { test, expect } from '@playwright/test';
test.describe('Registration Form Integration', () => {
test.beforeEach(async ({ page }) => {
// Mock the API response
await page.route('**/api/register', async route => {
const request = route.request();
const body = await request.postDataJSON();
if (body.email && body.email.includes('@')) {
await route.fulfill({
status: 200,
body: JSON.stringify({ message: 'Registration successful' })
});
} else {
await route.fulfill({
status: 400,
body: JSON.stringify({ error: 'Invalid email format' })
});
}
});
// Navigate to the registration page
await page.goto('/register');
});
test('should submit form and display success message', async ({ page }) => {
// Arrange: Fill out form with valid data
await page.fill('[data-testid="name-input"]', 'John Doe');
await page.fill('[data-testid="email-input"]', 'john@example.com');
await page.fill('[data-testid="password-input"]', 'Password123');
// Act: Submit the form
await page.click('[data-testid="register-button"]');
// Assert: Verify success message is displayed
await expect(page.locator('[data-testid="success-message"]')).toBeVisible();
await expect(page.locator('[data-testid="success-message"]')).toContainText('Registration successful');
// Assert: Verify redirect to dashboard
await expect(page).toHaveURL(/.*\/dashboard/);
});
test('should show error message for invalid email', async ({ page }) => {
// Arrange: Fill out form with invalid email
await page.fill('[data-testid="name-input"]', 'John Doe');
await page.fill('[data-testid="email-input"]', 'invalid-email');
await page.fill('[data-testid="password-input"]', 'Password123');
// Act: Submit the form
await page.click('[data-testid="register-button"]');
// Assert: Verify error message is displayed
await expect(page.locator('[data-testid="error-message"]')).toBeVisible();
await expect(page.locator('[data-testid="error-message"]')).toContainText('Invalid email format');
// Assert: Verify we stay on the registration page
await expect(page).toHaveURL(/.*\/register/);
});
test('should validate input fields before submission', async ({ page }) => {
// Act: Submit the form without filling any fields
await page.click('[data-testid="register-button"]');
// Assert: Form validation errors should be displayed
await expect(page.locator('[data-testid="name-error"]')).toBeVisible();
await expect(page.locator('[data-testid="email-error"]')).toBeVisible();
await expect(page.locator('[data-testid="password-error"]')).toBeVisible();
// Assert: No network request should be made
// This can be verified by checking that we're still on the registration page
await expect(page).toHaveURL(/.*\/register/);
});
});
TypeScript Example
import { test, expect } from '@playwright/test';
// Define types for the API responses
interface ProductType {
id: number;
name: string;
price: number;
inStock: boolean;
}
interface CartSuccessResponse {
message: string;
cartCount: number;
}
interface CartErrorResponse {
error: string;
}
test.describe('Shopping Cart Integration', () => {
test.beforeEach(async ({ page }) => {
// Mock the products API
await page.route('**/api/products', route => {
route.fulfill({
status: 200,
body: JSON.stringify([
{ id: 1, name: 'Product A', price: 19.99, inStock: true },
{ id: 2, name: 'Product B', price: 29.99, inStock: true },
{ id: 3, name: 'Product C', price: 39.99, inStock: false }
] as ProductType[])
});
});
// Mock the cart API
await page.route('**/api/cart/add', async route => {
const request = route.request();
const body = await request.postDataJSON();
if (body.productId === 3) {
await route.fulfill({
status: 400,
body: JSON.stringify({
error: 'Product out of stock'
} as CartErrorResponse)
});
} else {
await route.fulfill({
status: 200,
body: JSON.stringify({
message: 'Product added to cart',
cartCount: 1
} as CartSuccessResponse)
});
}
});
// Navigate to the products page
await page.goto('/products');
});
test('
… (hier gekürzt — Kopieren/Download liefert die vollständige Regel)
So nutzt du sie
Die Regel kopieren (Button oben) oder als Datei herunterladen und im Projekt unter .cursor/rules/ ablegen — Cursor lädt sie beim nächsten Start automatisch. Ältere Cursor-Versionen lesen alternativ eine einzelne .cursorrules-Datei im Projektstamm; dort einfach den Regel-Text ohne den Kopfblock zwischen den ----Zeilen einfügen.
Der Regel-Text ist englisch — Cursor versteht ihn unabhängig von der Sprache, in der Sie mit dem Editor chatten.
Im Detail
Diese Cursor-Regel sorgt dafür, dass die KI beim Schreiben von Playwright-Tests konsequent auf fokussierte Integrationstests setzt statt auf träge End-to-End-Läufe: Netzwerk-Requests werden gemockt, echte Backends bleiben außen vor. Das Ergebnis sind deutlich schnellere, stabilere Testsuiten, die sich gut in CI-Pipelines einbinden lassen, ohne dass Datenbank oder externe Dienste laufen müssen. Sinnvoll für Teams, die mit Cursor an Frontend- oder Fullstack-Projekten arbeiten und einheitliche Testkonventionen wollen, ohne sie bei jedem Prompt neu erklären zu müssen. Wer echte End-to-End-Abdeckung inklusive Backend braucht, sollte diese Regel um klassische E2E-Tests ergänzen.
Praxis-Tipp
Formulieren Sie Prompts wie „Schreibe einen Playwright-Test für den Login-Flow mit gemocktem API-Response“ – die Regel sorgt automatisch für saubere Mock-Struktur statt echter Requests.
Lizenz & Quelle
- Lizenz: CC0 1.0
- Quelle: PatrickJS/awesome-cursorrules (GitHub)
Inhalt ansehen (playwright-integration-testing.mdc)
Lade …
Erfahrungen & Kommentare.
Funktioniert der Regel bei Ihnen? Tipps, Stolperfallen, Varianten — teilen Sie es mit der Community.
Lade Kommentare …
Passt dazu.
AI Agent Specialist
Cursor-Regel für diszipliniertes, klar abgegrenztes Agenten-Verhalten statt unstrukturierter KI-Antworten.
Alpha Skills Quant Factor Research
Cursor-Regel für methodisch saubere quantitative Faktor-Recherche im Trading-Umfeld.
Android Jetpack Compose
Cursor-Regel für idiomatischen, deklarativen Android-UI-Code mit Jetpack Compose.
