Playwright Testing Guide: End-to-End-Tests für moderne Webanwendungen

Playwright Testing Guide: End-to-End-Tests für moderne Webanwendungen
https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Playwright_Logo.svg/330px-Playwright_Logo.svg.png
von Zelkulon17. März 20251 min Lesezeit

Playwright ist das leistungsfähigste E2E-Testing-Framework. Von der Installation bis zu robusten, wartbaren Tests – mit Next.js-Beispielen und CI/CD-Integration.

Playwright vs. Cypress

Playwright:                         Cypress:
──────────────────────────────────  ──────────────────────────────────
✓ Chromium, Firefox, WebKit         ✗ Primär Chromium
✓ Multi-Tab/Multi-Window            ✗ Keine echten Multi-Tabs
✓ Echte Parallelität                ✗ Nur mit Enterprise-Plan
✓ Trace-Viewer (Zeitreise-Debug)    ✗ Nur Video/Screenshots
✓ TypeScript nativ                  ✓ Ja

Konfiguration

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
    testDir: './e2e',
    fullyParallel: true,
    forbidOnly: !!process.env.CI,
    retries: process.env.CI ? 2 : 0,
    reporter: [['html'], ['github']],

    use: {
        baseURL: 'http://localhost:3000',
        trace: 'on-first-retry',
        screenshot: 'only-on-failure',
    },

    projects: [
        { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
        { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
        { name: 'mobile',   use: { ...devices['iPhone 14'] } },
    ],

    webServer: {
        command: 'npm run dev',
        url: 'http://localhost:3000',
        reuseExistingServer: !process.env.CI,
    },
});

Stabile Locators

// Beste Praxis: Role-basierte Locators (semantisch, stabil)
page.getByRole('button', { name: 'Absenden' });
page.getByRole('heading', { name: 'Kontakt' });
page.getByLabel('Deine E-Mail-Adresse');
page.getByPlaceholder('[email protected]');
page.getByTestId('submit-button');  // data-testid="..."

// Akzeptabel
page.getByText('Mehr erfahren');

// Vermeiden: CSS-Klassen (brechen bei Refactoring)
page.locator('.btn-primary');

// Nie: XPath
page.locator('xpath=//div[3]/button[1]');

Formular testen

test('sendet Kontaktformular erfolgreich ab', async ({ page }) => {
    await page.goto('/de/contact');

    await page.getByLabel('Dein Name').fill('Max Muster');
    await page.getByLabel('E-Mail').fill('[email protected]');
    await page.getByLabel('Nachricht').fill('Testnachricht.');

    await page.getByRole('button', { name: 'Absenden' }).click();

    await expect(page.getByText(/Danke für deine Nachricht/))
        .toBeVisible({ timeout: 10_000 });
});

test('zeigt Validierungsfehler bei leerem Formular', async ({ page }) => {
    await page.goto('/de/contact');
    await page.getByRole('button', { name: 'Absenden' }).click();

    await expect(page.getByText(/Name ist erforderlich/)).toBeVisible();
});

API-Mocking

test('zeigt Fehler bei API-Ausfall', async ({ page }) => {
    // API-Fehler simulieren
    await page.route('**/api/blog/posts*', async route => {
        await route.fulfill({ status: 500 });
    });

    await page.goto('/de/blog');
    await expect(page.getByText(/Fehler beim Laden/)).toBeVisible();
});

Page Object Model

// e2e/pages/BlogPage.ts
export class BlogPage {
    constructor(private readonly page: Page) {}

    async goto(locale = 'de') {
        await this.page.goto(`/${locale}/blog`);
    }
    async search(query: string) {
        await this.page.getByPlaceholder('Artikel suchen...').fill(query);
        await this.page.keyboard.press('Enter');
    }
    async getArticleCount() {
        return this.page.locator('[data-testid="blog-card"]').count();
    }
}

// Nutzung im Test
test('sucht Artikel', async ({ page }) => {
    const blogPage = new BlogPage(page);
    await blogPage.goto();
    await blogPage.search('Spring Boot');
    expect(await blogPage.getArticleCount()).toBeGreaterThan(0);
});

CI/CD – GitHub Actions

# .github/workflows/e2e.yml
- name: Install Playwright browsers
  run: npx playwright install --with-deps

- name: Run E2E tests
  run: npx playwright test
  env:
    CI: true

- name: Upload test report
  uses: actions/upload-artifact@v4
  if: always()
  with:
    name: playwright-report
    path: playwright-report/

Fazit

  • Zuverlässig: Auto-Warten auf Elemente eliminiert flaky Tests
  • Schnell: Echte Parallelität, kein Browser-Overhead
  • Debuggierbar: Trace Viewer macht Fehlersuche zur Zeitreise
  • Vollständig: Screenshot-Tests, API-Mocking, Multi-Browser
  • Tipp: Nur kritische User-Journeys abdecken, nicht jeden Klick
Playwright Testing Guide: End-to-End-Tests für moderne Webanwendungen