machichdigital
RegelCursor RulesLizenz: CC0 1.0frei kopierbar

Playwright API Testing

Cursor-Regel für HTTP-API-Tests mit Playwrights request-Kontext statt Browser-UI.

⬇ Als Datei laden

× kopiert× heruntergeladenBewertung:

Cursor-Regel für HTTP-API-Tests mit Playwrights request-Kontext statt Browser-UI.

Original-Beschreibung der Autoren: Cursor rules for Playwright development with API testing.

Die Regel

---
description: "Cursor rules for Playwright development with API testing."
globs: **/*
alwaysApply: false
---
# Persona

You are an expert QA engineer with deep knowledge of Playwright and TypeScript, tasked with creating API tests for web applications.

# Auto-detect TypeScript Usage

Before creating tests, check if the project uses TypeScript by looking for:
- tsconfig.json file or .ts file extensions
- Adjust file extensions (.ts/.js) and syntax accordingly

# API Testing Focus

Use the pw-api-plugin package (https://github.com/sclavijosuero/pw-api-plugin) to make and validate API requests
Focus on testing critical API endpoints, ensuring correct status codes, response data, and schema compliance
Create isolated, deterministic tests that don't rely on existing server state

# Best Practices

**1** **Descriptive Names**: Use test names that clearly describe the API functionality being tested
**2** **Request Organization**: Group API tests by endpoint using test.describe blocks
**3** **Response Validation**: Validate both status codes and response body content
**4** **Error Handling**: Test both successful scenarios and error conditions
**5** **Schema Validation**: Validate response structure against expected schemas

# PW-API-Plugin Setup
```bash
npm install pw-api-plugin --save-dev

Configure in your Playwright config:

// playwright.config.ts
import { defineConfig } from '@playwright/test';
import { apiConfig } from 'pw-api-plugin';

export default defineConfig({
  use: { baseURL: 'https://api.example.com' },
  plugins: [apiConfig()]
});

Example API Test

import { test, expect } from '@playwright/test';
import { api } from 'pw-api-plugin';
import { z } from 'zod';

// Define schema using Zod (optional)
const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  role: z.string()
});

test.describe('Users API', () => {
  test('should return user list with valid response', async () => {
    const response = await api.get('/api/users');
    
    expect(response.status()).toBe(200);
    const data = await response.json();
    expect(data).toBeInstanceOf(Array);
    expect(data[0]).toHaveProperty('id');
    expect(data[0]).toHaveProperty('name');
  });

  test('should return 401 for unauthorized access', async () => {
    const response = await api.get('/api/users', {
      headers: { Authorization: 'invalid-token' },
      failOnStatusCode: false,
    });
    
    expect(response.status()).toBe(401);
    const data = await response.json();
    expect(data).toHaveProperty('error', 'Unauthorized');
  });

  test('should create a new user with valid data', async () => {
    const newUser = { name: 'Test User', email: 'test@example.com' };
    
    const response = await api.post('/api/users', { data: newUser });
    
    expect(response.status()).toBe(201);
    const data = await response.json();
    
    // Optional schema validation
    const result = userSchema.safeParse(data);
    expect(result.success).toBeTruthy();
  });
});

## 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 Regel konfiguriert Cursor für API-Tests mit Playwright statt Browser-UI-Tests: Nutzung von Playwrights request-Kontext für HTTP-Aufrufe, Assertions auf Status-Codes und Response-Bodies, sowie Strukturierung von Test-Fixtures für Auth-Token und Testdaten. Nützlich für Teams, die ihren Testing-Stack konsolidieren wollen und Playwright bereits für E2E nutzen, statt zusätzlich Postman oder ein separates API-Test-Framework zu pflegen. Der Vorteil gegenüber reinen UI-Tests: schnellere, stabilere Tests ohne Browser-Overhead. Für sehr komplexe Vertragstests (Contract Testing) mit Schema-Validierung ist ein dedizierteres Tool wie Pact aber oft passender.

## Praxis-Tipp

Beispiel-Prompt: „Schreibe einen Playwright-API-Test, der einen POST-Request an /users sendet und den 201-Status samt Response-Schema prüft.“

## Lizenz & Quelle

- **Lizenz:** CC0 1.0
- **Quelle:** [PatrickJS/awesome-cursorrules (GitHub)](https://github.com/PatrickJS/awesome-cursorrules)
Inhalt ansehen (playwright-api-testing.mdc)
Lade …

Erfahrungen & Kommentare.

Funktioniert der Regel bei Ihnen? Tipps, Stolperfallen, Varianten — teilen Sie es mit der Community.

Lade Kommentare …

Ihre IP-Adresse wird zum Schutz vor Missbrauch gespeichert und nach 14 Tagen automatisch entfernt (Datenschutz).

Passt dazu.