Skip to main content
QA & Testing

Playwright End-to-End Testing

Production

Modern E2E browser automation, locators, assertions, auto-waiting, codegen, network mocking, and test runners.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

Playwright End-to-End Testing Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
Test Runner CLI--project, --ui
npx playwright test --project=chromium --headed --ui

Run test suite against Chromium browser in interactive UI debugger mode.

Code Generatorcodegen <url>
npx playwright codegen https://localhost:3000

Open interactive browser recorder that automatically outputs test scripts as you click.

Navigation & ActionsgetByRole, getByLabel
await page.goto('/login'); await page.getByLabel('Email').fill('test@user.com'); await page.getByRole('button', { name: 'Sign in' }).click();

Perform accessible user interactions with built-in auto-waiting.

Web Assertionsexpect().toBeVisible()
await expect(page).toHaveURL(/.*dashboard/); await expect(page.getByText('Welcome back')).toBeVisible();

Assert web state with automatic retry polling until assertions pass or timeout.

Network Interceptionpage.route()
await page.route('**/api/users', async (route) => { await route.fulfill({ status: 200, body: JSON.stringify([{ id: 1 }]) }); });

Mock API network requests to test edge cases without contacting real servers.

Full Page Screenshotscreenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });

Capture high-resolution full-page screenshot for visual regression testing.

Role-Based LocatorsgetByRole
await page.getByRole('button', { name: /submit/i }).click();

Target elements resiliently using accessible ARIA roles and regular expression names.

Network Response AwaitingwaitForResponse
await page.waitForResponse(r => r.url().includes('/api/data') && r.status() === 200);

Block test execution until a matching backend network response is successfully received.

API Mockingpage.route, route.fulfill
await page.route('**/api/user', async (route) => { await route.fulfill({ status: 200, json: { role: 'admin' } }); });

Intercept HTTP network requests and return mocked JSON payloads.

Execution Tracingtracing.start/stop
await context.tracing.start({ screenshots: true, snapshots: true }); // ... test steps await context.tracing.stop({ path: 'trace.zip' });

Record granular step-by-step DOM snapshots and network calls into zip trace files.

Trace Viewer Inspectionshow-trace
npx playwright show-trace trace.zip

Launch interactive visual trace viewer inspecting DOM state before and after every action.

Auth State ReusestorageState
test.use({ storageState: 'auth.json' });

Load pre-authenticated cookies and localStorage tokens skipping repeated login sequences.

Auto-Retrying AssertionstoBeVisible
await expect(page.getByTestId('status')).toBeVisible({ timeout: 10000 });

Poll element visibility continuously until assertion passes or timeout is reached.

Multi-Tab WorkflowswaitForEvent('page')
const [popup] = await Promise.all([context.waitForEvent('page'), page.click('a[target="_blank"]')]);

Handle new browser pop-up windows and secondary tab lifecycles asynchronously.

Dark Mode SimulationemulateMedia
await page.emulateMedia({ colorScheme: 'dark' });

Emulate operating system dark theme preference for visual regression testing.

Mobile ViewportssetViewportSize
await page.setViewportSize({ width: 375, height: 667 });

Simulate mobile screen dimensions to verify responsive navigation and layouts.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

Playwright End-to-End Testing: Command Groups & Quick Index

16 indexed entries across 16 sections
Test Runner CLI1 items
Code Generator1 items
Navigation & Actions1 items
Web Assertions1 items
Network Interception1 items
Full Page Screenshot1 items
Role-Based Locators1 items
Network Response Awaiting1 items
API Mocking1 items
Execution Tracing1 items
Trace Viewer Inspection1 items
Auth State Reuse1 items
Auto-Retrying Assertions1 items
Multi-Tab Workflows1 items
Dark Mode Simulation1 items
Mobile Viewports1 items

Highlighted Flags & Syntax Examples in Playwright End-to-End Testing

npx playwright test --project=chromium --headed --ui

Run test suite against Chromium browser in interactive UI debugger mode.

Flags: --project, --ui
npx playwright codegen https://localhost:3000

Open interactive browser recorder that automatically outputs test scripts as you click.

Flags: codegen <url>
await page.goto('/login'); await page.getByLabel('Email').fill('test@user.com'); await page.getByRole('button', { name: 'Sign in' }).click();

Perform accessible user interactions with built-in auto-waiting.

Flags: getByRole, getByLabel
await expect(page).toHaveURL(/.*dashboard/); await expect(page.getByText('Welcome back')).toBeVisible();

Assert web state with automatic retry polling until assertions pass or timeout.

Flags: expect().toBeVisible()

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for Playwright End-to-End Testing.

Why are Playwright tests less flaky than Selenium or Puppeteer?

Playwright has built-in auto-waiting. Before clicking, typing, or checking an element, Playwright automatically waits for the element to be visible, stable, enabled, and ready to receive events, eliminating arbitrary 'sleep()' statements.

Why are accessible locators (getByRole, getByLabel) recommended over CSS selectors?

Accessible locators mimic how real users and assistive screen readers navigate the page. They are resilient to implementation refactors (like changing CSS classes or tag names) and encourage accessible HTML design.

How does Playwright's Auto-Waiting mechanism eliminate flaky arbitrary sleep timers?

Before performing any action (click, fill, check), Playwright automatically runs a series of actionability checks: it verifies that the element is attached to the DOM, visible, stable (not animating), enabled, and not obscured by other elements. If any check fails, it waits and retries automatically until the timeout is reached.

What is the Playwright Trace Viewer and how does it simplify post-mortem test debugging?

The Trace Viewer is a post-mortem diagnostic GUI. It captures full DOM snapshots, screenshots, console logs, and network requests for every test step. You can scrub through a timeline to see the exact state of the DOM before and after each action, inspect console errors, and view API payloads without reproducing the test locally.

How does BrowserContext isolate test states without the overhead of restarting the browser process?

Playwright launches a single browser process and creates an isolated BrowserContext for each test. Each context operates like a fresh incognito browser profile with its own cookies, localStorage, and cache. Creating a context takes milliseconds, ensuring total test isolation without the CPU overhead of spinning up new browser binaries.

What is the difference between page.route() and external mock servers in end-to-end testing?

'page.route()' intercepts network requests at the browser engine level using Chrome DevTools Protocol / CDP, requiring zero external server setup. External mock servers (WireMock/MSW node) require server configuration and port binding. Browser-level routing allows conditional per-test mocking directly inside test specs.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets