Allscreenshots
Sign inGet an API key
Blog

Tutorial

Playwright End-to-End Testing Guide for Modern Web Apps

Alex ChenUpdated 10 min read

Playwright is a browser automation framework built for end-to-end testing. It lets you drive Chromium, Firefox, and WebKit with one API, write assertions against real pages, and debug failures with traces, videos, screenshots, and a visual test runner.

The reason teams adopt Playwright is not that it can click buttons. Selenium, Cypress, Puppeteer, and browser drivers can all do that. The reason is reliability: Playwright waits for elements to be actionable, isolates tests in fresh browser contexts, and gives you enough tooling to understand failures quickly.

This guide covers the practical pieces you need for a maintainable Playwright suite.

What Playwright Is Best At

Playwright is strongest when you need to verify complete user journeys:

  • Signup, login, and password reset flows
  • Checkout and billing flows
  • Search, filtering, and dashboard interactions
  • Cross-browser rendering differences
  • Mobile viewport behavior
  • JavaScript-heavy single-page applications
  • Regression tests for critical product paths

It is less useful for pure unit testing. If you only need to verify a helper function, use a unit test runner. If you need to verify that a user can complete a workflow in a real browser, use Playwright.

Install Playwright

For a Node.js project, start with:

bash
npm init playwright@latest

The installer creates a config file, example tests, and browser setup. Run the suite with:

bash
npx playwright test

Open the HTML report after a run:

bash
npx playwright show-report

A minimal test looks like this:

javascript
const { test, expect } = require('@playwright/test'); test('visitor can open the pricing page', async ({ page }) => { await page.goto('https://example.com/pricing'); await expect(page.getByRole('heading', { name: /pricing/i })).toBeVisible(); });

The important detail is the assertion. End-to-end tests should prove something meaningful about the page, not just open a URL.

How Playwright Reduces Flaky Tests

Most flaky browser tests fail because the test acts before the page is ready. Playwright avoids a lot of that with actionability checks.

Before clicking, Playwright checks that the target is:

  • Attached to the DOM
  • Visible
  • Stable
  • Enabled
  • Not covered by another element

That means this line already includes waiting behavior:

javascript
await page.getByRole('button', { name: 'Create account' }).click();

You usually do not need:

javascript
await page.waitForTimeout(3000);

Fixed sleeps make tests slower when the app is fast and unreliable when the app is slow. Prefer locators, web assertions, and app-specific readiness signals.

Use Locators That Match User Intent

Playwright's locator API encourages selectors based on what users see and assistive technologies understand.

javascript
await page.getByRole('button', { name: 'Save changes' }).click(); await page.getByLabel('Email address').fill('[email protected]'); await page.getByPlaceholder('Search projects').fill('billing'); await page.getByText('No invoices found').isVisible();

Role and label locators make tests more resilient than brittle CSS chains:

javascript
// Fragile: depends on implementation and styling await page.locator('.modal .footer .btn.primary').click(); // Better: describes the user-facing control await page.getByRole('button', { name: 'Confirm' }).click();

Use getByTestId when the UI text is not stable or when you need to target a technical state:

javascript
await page.getByTestId('billing-plan-pro').click();

Write Tests Around User Flows

A good Playwright test reads like a workflow:

javascript
const { test, expect } = require('@playwright/test'); test('user can create a project', async ({ page }) => { await page.goto('https://app.example.com/projects'); await page.getByRole('button', { name: 'New project' }).click(); await page.getByLabel('Project name').fill('Website redesign'); await page.getByRole('button', { name: 'Create project' }).click(); await expect(page).toHaveURL(/projects\/[a-z0-9-]+/); await expect(page.getByRole('heading', { name: 'Website redesign' })).toBeVisible(); await expect(page.getByText('Project created')).toBeVisible(); });

Notice what the test does not assert:

  • It does not check every class name
  • It does not inspect internal component state
  • It does not repeat assertions already covered by unit tests

End-to-end tests are expensive compared with unit tests. Spend them on paths that matter.

Handle Authentication Without Repeating Login

Logging in through the UI before every test is slow and can make unrelated tests fail when the login page changes.

Use Playwright's storage state feature to authenticate once and reuse the session:

javascript
// tests/auth.setup.js const { test: setup, expect } = require('@playwright/test'); setup('authenticate', async ({ page }) => { await page.goto('https://app.example.com/login'); await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL); await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD); await page.getByRole('button', { name: 'Sign in' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); await page.context().storageState({ path: 'playwright/.auth/user.json' }); });

Then reference it in config:

javascript
module.exports = { projects: [ { name: 'setup', testMatch: /.*\.setup\.js/ }, { name: 'chromium', use: { storageState: 'playwright/.auth/user.json' }, dependencies: ['setup'] } ] };

This keeps product-flow tests focused on the product flow, not on repeated login mechanics.

Test Across Browsers and Devices

Playwright can run the same test suite against multiple browser engines.

javascript
const { devices } = require('@playwright/test'); module.exports = { projects: [ { name: 'chromium', use: { browserName: 'chromium' } }, { name: 'firefox', use: { browserName: 'firefox' } }, { name: 'webkit', use: { browserName: 'webkit' } }, { name: 'mobile-chrome', use: { ...devices['Pixel 7'] } }, { name: 'mobile-safari', use: { ...devices['iPhone 14'] } } ] };

You do not need every browser on every test at first. A practical setup is:

  • Run critical smoke tests across all browsers
  • Run the full suite on Chromium
  • Add mobile projects for flows where layout changes materially

This gives broad coverage without turning every pull request into a slow browser matrix.

Mock Network Calls When It Improves Signal

End-to-end tests should exercise real integrations where that matters. But for flows dominated by volatile APIs, network mocking can reduce noise.

javascript
test('shows the empty invoice state', async ({ page }) => { await page.route('**/api/invoices', async (route) => { await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ invoices: [] }) }); }); await page.goto('https://app.example.com/billing'); await expect(page.getByText('No invoices yet')).toBeVisible(); });

Use mocks for:

  • Rare error states
  • Empty states
  • Slow third-party APIs
  • Payment or email providers
  • Data that would otherwise change between runs

Keep at least a few smoke tests wired to real backend paths so the suite still catches integration issues.

Debug Failures with Traces

Playwright traces are one of its best features. Configure traces for retries:

javascript
module.exports = { retries: process.env.CI ? 2 : 0, use: { trace: 'on-first-retry', screenshot: 'only-on-failure', video: 'retain-on-failure' } };

Open a trace with:

bash
npx playwright show-trace trace.zip

The trace viewer shows DOM snapshots, console logs, network requests, screenshots, timing, and each Playwright action. Instead of guessing why CI failed, you can inspect what the browser saw.

For local debugging:

bash
npx playwright test --ui npx playwright test --debug npx playwright test --headed

UI mode is useful for exploring failures and rerunning a single test while you edit.

Run Playwright in CI

A basic GitHub Actions workflow:

yaml
name: Playwright on: pull_request: push: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: node-version: 20 - run: npm ci - run: npx playwright install --with-deps - run: npx playwright test - uses: actions/upload-artifact@v4 if: failure() with: name: playwright-report path: playwright-report/

For faster CI, cache dependencies, split large suites into shards, and run browser projects selectively.

bash
npx playwright test --shard=1/4 npx playwright test --shard=2/4 npx playwright test --shard=3/4 npx playwright test --shard=4/4

Playwright vs Screenshot APIs

Playwright can take screenshots:

javascript
await page.screenshot({ path: 'dashboard.png', fullPage: true });

That is useful inside a test, especially for failure artifacts. But screenshot-heavy workflows often need more than a local browser call:

  • Capture many URLs on a schedule
  • Block ads and cookie banners
  • Generate full-page screenshots without tuning browser infrastructure
  • Produce consistent screenshots for visual regression baselines
  • Run captures from jobs that do not need a full Playwright suite

For those cases, use AllScreenshots screenshot automation alongside Playwright:

javascript
const response = await fetch('https://api.allscreenshots.com/v1/screenshots', { method: 'POST', headers: { 'X-API-Key': process.env.SCREENSHOT_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ url: 'https://example.com', fullPage: true, viewport: { width: 1440, height: 900 }, format: 'png' }) });

Use Playwright to prove behavior. Use AllScreenshots for repeatable screenshot capture, visual regression testing, scheduled screenshots, and documentation workflows.

When to Choose Playwright

NeedRecommendation
Test a real user journeyPlaywright
Verify cross-browser behaviorPlaywright
Unit test business logicUnit test runner
Capture many URLs on a scheduleScreenshot API
Generate visual baselinesPlaywright or Screenshot API
Monitor production pages visuallyWebsite monitoring

Playwright is a strong default for end-to-end testing because it balances realistic browser coverage with practical developer tooling.

Conclusion

Playwright gives teams a reliable way to test modern web applications in real browsers. Start with a few critical user flows, use locators that match user intent, avoid fixed waits, capture traces in CI, and expand browser coverage as the suite proves its value.

For screenshot-specific workloads, pair it with AllScreenshots so your test suite does not become a screenshot infrastructure project.

Find out how easy it is to capture and share pixel-perfect screenshots at scale using Allscreenshots. Sign up for a free account and start integrating your first screenshot API call today.

Start with one request

Free plan: 100 screenshots. No credit card.

Get an API key
  • Full-page captures
  • Popups and repeated sticky bars removed
  • Markdown, JSON and PDF output
  • Crawl a site from one URL
  • Desktop, tablet and phone in one image
  • Works in n8n, Make and Zapier
  • MCP server for AI assistants