Playwright End-to-End Testing Tutorial
On this page
Learning Objective
Write reliable browser tests for the critical user journeys with Playwright, authenticate once and reuse the session, avoid the causes of flakiness, verify security properties that only a real browser can show such as cookie flags and CSP violations, and run the suite safely in a pipeline against a test environment.
Concept Explanation
End-to-end tests are the only tests that exercise everything together: the built React bundle, the BFF, the API, the database, and the identity provider, all in a real browser. That completeness is why they are valuable and also why they are expensive, slow, and fragile if written carelessly. The right strategy is to have few of them, covering the journeys that would be catastrophic to break, such as signing in, creating a project, moving a task, and signing out, and to push everything else down to the faster layers. A suite of three to ten well-built journeys run after every deployment to a test environment gives a real signal that the system is alive and wired correctly.
Playwright, developed at Microsoft by the team that previously built Puppeteer at Google, is the current standard. It drives Chromium, Firefox, and WebKit, waits automatically for elements to be ready before interacting, and provides locators that find elements by role, label, and text, the same principles as Testing Library. Its web-first assertions retry until a condition becomes true or a timeout passes, so you write expect a locator to be visible instead of sleeping and hoping. The trace viewer records a timeline of each test with DOM snapshots, network calls, and console output, which turns a red build in CI into a debuggable recording instead of a mystery. Most flakiness comes from three habits to avoid: fixed sleeps, brittle selectors tied to CSS structure, and tests that depend on each other's data.
Authentication is the part that needs planning. Logging in through the real identity provider for every test is slow and can trip its protections. The standard approach is a setup step that signs in once with a dedicated test account and saves the browser storage state, the cookies, to a file, and every test then starts already signed in by loading that file. The test account should live in a dedicated test tenant with no access to production data, its credentials should come from the CI secret store, and it should have only the roles the tests need. Create test data through the API, using an authenticated request, rather than clicking through screens, and give each run unique names so that parallel runs and leftovers do not collide.
A real browser can verify security properties that lower layers cannot. You can read the cookies the browser actually holds and assert that the session cookie is HttpOnly, Secure, and SameSite, and that no token appears in localStorage or sessionStorage. You can listen for securitypolicyviolation events and fail the test if the application triggers a Content Security Policy violation, which catches a new inline script or third-party resource that would break under the policy. You can test that the login return URL cannot redirect to another site, that a signed-out user is bounced from protected pages, and that the page passes an automated accessibility scan. These checks cost a few lines each and guard properties that are easy to break by accident during a refactor.
| Concern | Technique | Note |
|---|---|---|
| Finding elements | getByRole, getByLabel, getByText | Same accessible queries as component tests |
| Waiting | Auto-waiting and web-first assertions | No fixed sleeps |
| Authentication | Setup project saves storageState once | Dedicated test tenant and account, secrets from CI |
| Test data | Create through the API with unique names | Independent tests, safe in parallel |
| Debugging | Trace viewer, screenshots, video on failure | Attach as CI artifacts |
| Browser-only security checks | Cookie flags, storage contents, CSP events | Cheap, catches accidental regressions |
Worked Example: Configuration, Auth Setup, a Journey and Security Assertions
The configuration defines a setup project and the browsers. The journey test moves a card. The security spec checks cookies, storage and CSP.
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
retries: process.env.CI ? 1 : 0, // one retry in CI, and track anything that needed it
reporter: [['html', { open: 'never' }], ['list']],
use: {
baseURL: process.env.E2E_BASE_URL, // staging or a per-PR preview, never production
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{ name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' }, dependencies: ['setup'] },
{ name: 'webkit', use: { ...devices['Desktop Safari'], storageState: '.auth/user.json' }, dependencies: ['setup'] },
],
});
// e2e/auth.setup.ts: sign in once with the dedicated test account, save the session cookie.
import { test as setup, expect } from '@playwright/test';
setup('sign in', async ({ page }) => {
await page.goto('/bff/login?returnUrl=/');
await page.getByLabel('Email').fill(process.env.E2E_USER!); // from the CI secret store
await page.getByRole('button', { name: 'Next' }).click();
await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible();
await page.context().storageState({ path: '.auth/user.json' }); // .auth/ is in .gitignore
});// e2e/board.spec.ts: one critical journey, data created through the API.
import { test, expect } from '@playwright/test';
test('a member can create a task and move it across the board', async ({ page, request }) => {
const suffix = crypto.randomUUID().slice(0, 8);
const project = await (await request.post('/api/projects', {
data: { name: `E2E ${suffix}` }, headers: { 'X-CSRF': '1' },
})).json();
await page.goto(`/projects/${project.id}`);
await page.getByRole('button', { name: 'Add task' }).click();
await page.getByLabel('Title').fill(`Write report ${suffix}`);
await page.getByRole('button', { name: 'Save task' }).click();
const card = page.getByRole('listitem').filter({ hasText: `Write report ${suffix}` });
await expect(card).toBeVisible();
await card.getByLabel(/^Move /).selectOption('inProgress');
await expect(page.getByRole('group', { name: 'In progress' }).getByText(`Write report ${suffix}`)).toBeVisible();
await page.reload(); // the move really persisted on the server
await expect(page.getByRole('group', { name: 'In progress' }).getByText(`Write report ${suffix}`)).toBeVisible();
});// e2e/security.spec.ts: properties only a real browser can prove.
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('the session cookie is locked down and no tokens live in web storage', async ({ page, context }) => {
await page.goto('/');
const cookie = (await context.cookies()).find((c) => c.name === '__Host-bff');
expect(cookie, 'session cookie present').toBeDefined();
expect(cookie!.httpOnly).toBe(true);
expect(cookie!.secure).toBe(true);
expect(['Lax', 'Strict']).toContain(cookie!.sameSite);
const storage = await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }));
expect(storage).not.toMatch(/eyJ[A-Za-z0-9_-]{10,}\./); // nothing that looks like a JWT
});
test('the app triggers no Content Security Policy violations on key pages', async ({ page }) => {
const violations: string[] = [];
await page.exposeFunction('reportViolation', (v: string) => violations.push(v));
await page.addInitScript(() =>
document.addEventListener('securitypolicyviolation', (e) =>
(window as any).reportViolation(`${e.violatedDirective}: ${e.blockedURI}`)));
for (const path of ['/', '/settings']) { await page.goto(path); await page.waitForLoadState('networkidle'); }
expect(violations).toEqual([]);
});
test('a hostile return url does not leave the site', async ({ page }) => {
await page.goto('/bff/login?returnUrl=//evil.example/phish');
await page.waitForLoadState('networkidle');
expect(new URL(page.url()).hostname).not.toBe('evil.example');
});
test('the projects page has no serious accessibility violations', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.filter((v) => ['serious', 'critical'].includes(v.impact ?? ''))).toEqual([]);
});# CI (excerpt): run against the deployed test environment, keep the evidence.
- run: npx playwright install --with-deps chromium webkit
- run: npx playwright test
env: { E2E_BASE_URL: "${{ vars.STAGING_URL }}", E2E_USER: "${{ secrets.E2E_USER }}", E2E_PASSWORD: "${{ secrets.E2E_PASSWORD }}" }
- uses: actions/upload-artifact@v4
if: failure()
with: { name: playwright-report, path: playwright-report/ }Keep the number of journeys small and treat a retry that rescued a test as a defect to investigate, because a test that passes only on the second try is hiding a race in either the test or the application.
Real-World Examples
- Playwright was created at Microsoft in 2020 by engineers including Andrey Lushnikov and Pavel Feldman, who had previously worked on Puppeteer at Google. It added cross-browser support, auto-waiting, and the trace viewer, and has become one of the most widely adopted browser automation tools, largely displacing older Selenium-based suites in new projects because of its reliability.
- Google's testing blog has documented how large end-to-end suites become the least reliable part of a pipeline because failures can come from any of many components, and recommends keeping them few and focused on critical user journeys. The same experience is why the security checks here run as small assertions inside those journeys instead of as a separate large suite.
Review Questions & Answers
Fixed sleeps, selectors tied to layout details, and shared or leftover test data. Playwright waits automatically for elements to be actionable, offers role and label locators that survive markup changes, and retrying web-first assertions replace sleeps. Independent tests with unique data created through the API remove the dependence on other tests.
A test account with production access would let a bug or a leaked credential affect real data, and hard-coded credentials in the repository can be stolen. A dedicated tenant with minimal roles limits the blast radius, and injecting credentials from the secret store keeps them out of source control and logs.
It observes what the real browser holds and enforces: the actual cookie attributes, the contents of localStorage and sessionStorage, Content Security Policy violation events triggered by real page loads, and how the browser handles redirects. These behaviors depend on the browser and the fully assembled application, so they can only be proven end to end.
It indicates nondeterminism, either a race in the test or a real timing bug in the application that users may also hit. Retries hide it and let it accumulate until the suite becomes unreliable. Tracking tests that needed retries and fixing their causes keeps the suite trustworthy.