Playwright Testing Guide: End-to-End Tests for Modern Web Applications

Playwright Testing Guide: End-to-End Tests for Modern Web Applications
https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Playwright_Logo.svg/330px-Playwright_Logo.svg.png
by Zelkulon17 March 20251 min read

Playwright is the most powerful E2E testing framework. From installation to robust, maintainable tests – with Next.js examples and CI/CD integration.

Playwright vs. Cypress

Playwright:                         Cypress:
──────────────────────────────────  ──────────────────────────────────
βœ“ Chromium, Firefox, WebKit         βœ— Primarily Chromium
βœ“ Multi-Tab/Multi-Window            βœ— No real multi-tabs
βœ“ True parallelism                βœ— Only with Enterprise plan
βœ“ Trace-Viewer (time-travel debug)    βœ— Only video/screenshots
βœ“ TypeScript nativ                  βœ“ Yes

Configuration

// 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,
    },
});

Stable Locators

// Best practice: role-based locators (semantic, stable)
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="..."

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

// Avoid: CSS classes (break on refactoring)
page.locator('.btn-primary');

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

Testing a Form

test('submits contact form successfully', 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('shows validation errors on empty form', 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('shows error on API failure', async ({ page }) => {
    // simulate API error
    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();
    }
}

// Usage in test
test('searches for articles', 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/

Summary

  • Reliable: auto-waiting for elements eliminates flaky tests
  • Fast: true parallelism, no browser overhead
  • Debuggable: Trace Viewer turns debugging into time travel
  • Complete: screenshot tests, API mocking, multi-browser
  • Tip: cover only critical user journeys, not every click
Playwright Testing Guide: End-to-End Tests for Modern Web Applications