Playwright·Cookbook Field Manual
Part 01 · Network Mocking Card 01

First Browser Test

Card 01: First Browser Test

What This Pattern Solves

Before you can mock APIs, you need to understand basic browser automation: opening a page, waiting for elements, and making assertions. This card shows the fundamentals WITHOUT mocking - you’ll see what happens when the real API is called (or fails).

How It Works

  1. We simulate the external API being unavailable with page.route() returning a 500
  2. Playwright opens the browser and navigates to /cards/01 (the person demo page)
  3. The page tries to fetch the person and gets the failing response
  4. We assert on the page structure and error state, not on successful data

This demonstrates why mocking is valuable: tests that depend on external APIs are slow and flaky. When SWAPI fails (which happens frequently), the page shows an error message - which is what we test here. Here we force that failure so the outcome is deterministic.

Code Example

import { test, expect } from '@playwright/test';

test.describe('01-first-browser-test: Open browser and assert on page', () => {
  // @smoke: a fast, always-run sanity check. Selective run: `--grep @smoke`.
  test('shows an error when the external API fails', { tag: '@smoke' }, async ({ page }) => {
    // Simulate the real SWAPI being unavailable. Without mocking, a flaky
    // external dependency makes this the outcome you cannot control.
    await page.route('**/swapi.dev/api/people/**', (route) =>
      route.fulfill({ status: 500 }),
    );

    await page.goto('/cards/01');

    await expect(page.getByRole('heading', { name: 'Person' })).toBeVisible();
    await expect(page.getByTestId('error')).toBeVisible();
  });
});

A single page.route() forces the failure - the rest is just navigation and assertions.

Run This Example

pnpm test src/01-first-browser-test

Note: This test expects SWAPI to fail (which it often does). If SWAPI is working, the test may fail - demonstrating exactly why we need mocking! Card 02 fixes this with deterministic mocking.

Prerequisites

None - start here. This is your first Playwright test.

Key Concepts

When to Use This Pattern

Common Mistakes

Flow Diagram

sequenceDiagram
    participant Test
    participant Browser
    participant Page
    participant SWAPI

    Test->>Browser: page.goto('/cards/01')
    Browser->>Page: Load HTML/JS
    Page->>SWAPI: fetch('/people/1')
    Note over SWAPI: Forced 500 via page.route()
    SWAPI--xPage: 500 error
    Page->>Browser: Render error message
    Test->>Browser: expect heading visible ✓
    Test->>Browser: expect error visible ✓

Live Demo

👇 This component is what the Playwright test interacts with:

Loading…

Run This Example

pnpm test src/01-first-browser-test