ScreenshotNeo

BlogGuides

Playwright: Getting Started with the Browser Automation Tool

Install Playwright, write and run your first browser test, then inspect failures with the CLI, UI mode, and traces.

By the ScreenshotNeo team4 October 20268 min read

Playwright Test is an end-to-end testing framework for web apps. It combines a test runner, assertions, isolated browser contexts, parallel execution, and debugging tools. To get started, initialize it in a JavaScript or TypeScript project, install the browser binaries for your configured projects, write a test that performs an action and checks an observable result, and run it with the CLI.

This guide uses the stable Playwright documentation. Runtime requirements and browser builds can change, so check the current installation guide against your operating system before setup.

1. Initialize a Playwright project

Use the package manager already used by your project. The initializer creates a test directory, a configuration file, an example test, and can install browser binaries and add a GitHub Actions workflow.

# npm
npm init playwright@latest

# Yarn
yarn create playwright

# pnpm
pnpm create playwright

Choose JavaScript or TypeScript when prompted, select the test directory, and decide whether to add the optional CI workflow and install browsers now. Review the generated playwright.config.ts, package manifest, lockfile, and example test before committing. You can run the initializer again later; the setup guide says it does not overwrite existing tests.

Check the runtime and operating system

The Playwright Next documentation lists Node.js 22.x, 24.x, or 26.x and operating systems including Windows 11 or newer, Windows Server 2019 or newer, WSL, macOS 14 or newer, and specified Debian and Ubuntu releases on x86-64 or arm64. That is the Next page’s stated support information, not a promise that other environments cannot work. Verify the stable documentation and your environment before setting up a CI image.

2. Install matching browser binaries

Playwright releases expect browser binaries associated with that release. Install the browsers needed by your configured projects:

# Install the default browser set
npx playwright install

# Install only Chromium
npx playwright install chromium

# On Linux, install browser system dependencies too
npx playwright install --with-deps

# Or install dependencies separately
npx playwright install-deps

Default projects commonly cover Chromium, Firefox, and WebKit. Browser downloads take disk space in an OS-specific cache, and their size varies by release. If you update Playwright and see a missing-browser error, run the install command again so the binaries match the package version.

Playwright’s Chromium build is distinct from branded Google Chrome and Microsoft Edge. Those branded browsers are not installed by default. Use a Chrome or Edge channel when the distribution itself is part of what you need to test; otherwise the docs recommend the default Chromium setup for most cases. See the browser documentation for channels, cache locations, proxy configuration, and browser management commands.

3. Write your first test

Create tests/first.spec.ts (or a JavaScript file if you selected JavaScript). This example opens the Playwright home page, checks its title, follows a link by accessible role and name, and asserts that the destination heading is visible.

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

test('navigate from the home page to the documentation', async ({ page }) => {
  await page.goto('https://playwright.dev/');

  await expect(page).toHaveTitle(/Playwright/);

  await page.getByRole('link', { name: 'Get started' }).click();
  await expect(
    page.getByRole('heading', { name: 'Installation' })
  ).toBeVisible();
});

Run this against the current Playwright site. If its navigation label or heading changes, inspect the page and update the accessible name to match. For your own application, replace the URL and expected content with a stable page and outcome.

Why this test is a useful starting point

  • page is a fixture that gives the test a page to control. Tests get isolated browser contexts, which helps keep state from leaking between tests.
  • getByRole finds an element by its accessible role and name. This is generally more resilient and meaningful than selecting an element by its position in the DOM.
  • click() waits for the actionability checks Playwright needs before interacting with the element.
  • toHaveTitle and toBeVisible are web-first assertions: they retry while the expected state has not appeared, up to the assertion timeout.

A test should check a user-visible outcome after an action. Avoid fixed sleeps as a default synchronization strategy; they add time and can still miss the state you intended to observe. See Writing tests for locators, assertions, fixtures, and isolation.

4. Run tests and choose browsers

Run the configured suite from the project directory:

npx playwright test

Tests run headlessly by default. The configured projects determine which browser engines run. Use the following commands when you need a different view or a narrower run:

# Show browser windows while tests run
npx playwright test --headed

# Open interactive UI mode
npx playwright test --ui

# Run one configured project (replace chromium with its project name)
npx playwright test --project=chromium

# Run one test file
npx playwright test tests/first.spec.ts

# Open the HTML report after a run
npx playwright show-report

UI mode provides step inspection, watch mode, a locator picker, and trace integration. Headed mode is useful when you want to see the interaction directly. The CLI is sufficient for the basic workflow; the running and debugging guide documents more options, including retries and report configuration.

5. Configure a browser matrix and test behavior

The generated configuration centralizes browser projects, timeouts, retries, and reporters. A project represents a browser configuration; run a single project while diagnosing a failure, or run all configured projects to cover the matrix.

A minimal configuration can look like this when the corresponding browsers have been installed:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  expect: { timeout: 5_000 },
  retries: process.env.CI ? 2 : 0,
  reporter: process.env.CI ? 'github' : 'html',
  use: {
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
});

This configuration is illustrative: keep or adjust the generated defaults to suit your suite. Retry settings can help preserve diagnostic output on intermittent CI failures, but a test that passes only on retry still deserves investigation. Browser, OS, headed/headless, local/CI, and mobile-emulation needs are useful axes for choosing projects. Playwright also supports native mobile emulation profiles for Chrome on Android and Mobile Safari; emulation is not a substitute for every real-device check.

Use branded Chrome or Edge when distribution matters

If your test needs branded Chrome or Edge specifically, install or make the relevant browser available and configure its channel in a project. The documentation distinguishes these installed branded browsers from Playwright’s own Chromium build. Use the browser channel guidance for the current channel names and setup.

6. Inspect a failure

  1. Read the terminal output to identify the failed test, assertion, and action.
  2. Run with --headed if seeing the browser interaction will clarify the issue.
  3. Run with --ui to step through execution and inspect the action timeline.
  4. Open the HTML report with npx playwright show-report.
  5. If traces are configured, open the trace from the report or UI mode to inspect snapshots and actions around the failure.

The Playwright VS Code extension is optional. It adds Test Explorer integration, individual run and debug controls, a browser display, test recording, locator picking, and trace viewing. See the VS Code guide. For a CI workflow, follow the official Continuous Integration guide and use an environment compatible with the selected Playwright release.

7. Troubleshoot common setup and test failures

Symptom Likely cause Fix
Executable or browser missing at launch The Playwright package was updated, or the browser install step was skipped. Run npx playwright install, or install only the project’s engine. Keep package and browser versions aligned.
Browser fails to launch on Linux Required operating-system libraries are absent. Use npx playwright install --with-deps or npx playwright install-deps on a supported Linux environment.
Chrome or Edge channel cannot be found Branded Chrome and Edge are not bundled with the normal Playwright browser install. Install the branded browser or use Playwright’s default browser build. Confirm the project’s channel setting matches the installed browser.
Browser download fails behind a corporate network A proxy, artifact repository, or certificate trust configuration blocks the download. Use the documented proxy or custom download-host settings, and supply the trusted custom root certificate where needed. Do not disable certificate checks.
Click times out because the locator finds nothing The accessible name or role differs from the page, or the page has not reached the expected state. Inspect the rendered page with UI mode or a trace, correct the role/name locator, and assert an appropriate prerequisite state.
Assertion times out although navigation worked The expected title, heading, or visible state is wrong, or the app did not reach that state. Inspect the page and trace, verify the expected result manually, and update the assertion only if the product behavior is correct.
Test is flaky in CI but passes locally Environment differences, timing assumptions, shared state, or a missing dependency can affect execution. Use web-first assertions instead of arbitrary sleeps, keep tests isolated, install OS dependencies, and inspect traces from CI. Check runtime and browser compatibility.
HTML report is not available The run did not use an HTML reporter, or the report has not been generated. Configure the HTML reporter, rerun the suite, then use npx playwright show-report.

8. Performance, reliability, and maintenance

  • Parallel work: Playwright can run tests in parallel. Begin with the generated configuration, then tune workers to the CPU and memory available locally or in CI; more workers can increase contention.
  • Reliability: Use isolated tests, semantic locators, automatic actionability waits, and retrying assertions. Avoid shared mutable test data and fixed delays where an observable condition can be asserted.
  • Debuggability: Configure traces for failures or retries and retain the HTML report in CI when it is useful to investigate a run.
  • Browser maintenance: Update browser binaries after Playwright package updates. Browser builds, runtime support, and operating-system requirements are version-sensitive.
  • Cost: Playwright is downloaded software; budget for CI compute, browser storage, test runtime, and any hosted infrastructure your pipeline uses. The reviewed setup documentation does not establish a universal runtime or disk-size figure.

Or skip the browser setup

If your goal is to capture a web page image rather than test browser behavior, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns an image or PDF; see the API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Create a free account and get 1,000 screenshots a month with no card.

FAQ

Can I use Playwright with JavaScript as well as TypeScript?

Yes. The initializer lets you choose either language, and the same basic test structure applies.

Do I need the VS Code extension?

No. You can initialize, run, and debug tests with the CLI. The extension adds editor conveniences.

Should I test every browser engine on every change?

That depends on your application’s support targets and CI budget. Configure projects for the engines and distributions that matter, and use project selection to focus a run when diagnosing it.

Is browser emulation the same as testing on a phone?

No. Playwright provides mobile emulation profiles, but emulation does not replace checks on physical devices when hardware or platform behavior matters.