Define browser end-to-end scenarios
Choose an end-to-end journey
End-to-end (E2E) testing follows a user journey through a running application in a real browser. It complements unit and component tests: it can reveal broken navigation, missing assets and incorrectly connected forms. A browser test with a mocked API checks the frontend contract, not the actual server. This chapter uses a fictional repair desk: a visitor opens a ticket form, enters a description and sees a receipt or a recoverable error. Use synthetic records, not real customer data. A direct visit to /tickets/new should work as well as navigation from the home page.
import React, { useState } from 'react';export default function App() { const [description, setDescription] = useState(''); const [status, setStatus] = useState('idle'); async function submit(event) { event.preventDefault(); const text = description.trim(); if (!text || status === 'pending') return; setStatus('pending'); try { const response = await fetch('/api/tickets', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({description: text}) }); if (!response.ok) throw new Error('Rejected'); setStatus('success'); setDescription(''); } catch { setStatus('error'); } } return <main><h1>Repair desk</h1><a href="/tickets/new">New ticket</a> {location.pathname === '/tickets/new' && <form onSubmit={submit}> <label htmlFor="description">Description</label> <input id="description" required maxLength={120} value={description} onChange={e => setDescription(e.target.value)} /> <button disabled={status === 'pending' || !description.trim()}>Send ticket</button> <p role="status">{status === 'success' ? 'Ticket received' : status === 'pending' ? 'Sending' : ''}</p> {status === 'error' && <p role="alert">Could not send. Try again.</p>} </form>} </main>;}The small example uses ordinary links and reads the current path on page load; it is not a router implementation. A Vite preview server must serve the SPA entry at the deep link. The form retains text after an error and clears it after success. This is a staged client, not a real service; production must validate and authorize the request and prevent duplicate submissions at the server. No actual request is needed in the offline test lane.
Locate controls by meaning and assert observable results
import { test, expect } from '@playwright/test';test('opens the form and sends a ticket', async ({page}) => { await page.route('**/api/tickets', async route => { expect(route.request().method()).toBe('POST'); expect(route.request().postDataJSON()).toEqual({description:'Loose handle'}); await route.fulfill({status:201, json:{id:'demo-1'}}); }); await page.goto('/'); await page.getByRole('link',{name:'New ticket'}).click(); await expect(page).toHaveURL(/\/tickets\/new$/); await page.getByLabel('Description').fill('Loose handle'); await page.getByRole('button',{name:'Send ticket'}).click(); await expect(page.getByRole('status')).toHaveText('Ticket received'); await expect(page.getByLabel('Description')).toHaveValue('');});A locator resolves the current element when an action or assertion runs. Playwright checks relevant actionability conditions and web-first assertions retry until their timeout. Avoid arbitrary sleeps: wait for the user-visible receipt instead of guessing how long a request takes. Register routes before navigation if early requests matter. A role/name locator is usually more resilient than a chain of CSS classes, but it does not certify accessibility.
Test failure and recovery from a deep link
import { test, expect } from '@playwright/test';test('retains the input on failure and permits retry', async ({page}) => { let attempts = 0; await page.route('**/api/tickets', route => route.fulfill( ++attempts === 1 ? {status:503, json:{}} : {status:201, json:{id:'demo-2'}})); await page.goto('/tickets/new'); const input = page.getByLabel('Description'); await input.fill('Loose hinge'); await page.getByRole('button',{name:'Send ticket'}).click(); await expect(page.getByRole('alert')).toHaveText('Could not send. Try again.'); await expect(input).toHaveValue('Loose hinge'); await page.getByRole('button',{name:'Send ticket'}).click(); await expect(page.getByRole('status')).toHaveText('Ticket received'); await expect(page.getByRole('alert')).toHaveCount(0); expect(attempts).toBe(2);});The mock returns a controlled 503 then 201. Each test owns its attempt counter; retries of the test should start from a fresh counter. This checks the client response to a server failure, not whether a real backend recovers. Practice: add a test that empty and whitespace-only input cannot submit. Verify zero intercepted POST requests, not just a disabled-looking button.