FROMDEV

How to Build a Browser Automation Test with Playwright

How to Build a Browser Automation Test with Playwright

Build Reliable Browser Tests with Playwright: A Practical Guide

Playwright helps developers automate real browser interactions and check that web applications behave as expected. To build a useful browser automation test, install Playwright Test, describe a user journey with resilient locators, add clear assertions, and run the test across the browsers your project supports. This guide walks through that process, including a working example, page objects, debugging techniques, and common trade-offs.

What Is Playwright Browser Automation?

Playwright is an open-source browser automation library and testing framework. Its Playwright Test runner can launch Chromium, Firefox, and WebKit, interact with pages, and report whether tests pass. It supports features such as auto-waiting for many actions and assertions, isolated browser contexts, screenshots, and trace recording.

Browser automation testing is most useful for checking critical user journeys: signing in, searching, submitting a form, or completing a purchase. It complements unit and API tests; it should not replace them. Browser tests exercise more of the application, but they are generally slower and can be more sensitive to environmental problems.

When planning coverage, consider which browsers and environments your users rely on. For a broader look at browser settings and options, see What are the Browser Configurations?

Install Playwright Test

For a Node.js project, create a package configuration if needed, then install the Playwright Test package and its browser binaries:

npm init playwright@latest

The setup command creates a basic test configuration and example tests. Follow its prompts to choose JavaScript or TypeScript and whether to add a CI workflow. If you are adding Playwright to an existing project, you can install the package directly:

npm install --save-dev @playwright/test
npx playwright install

The install command downloads browser binaries supported by the installed Playwright version. In a Linux CI environment, you may also need the required operating-system dependencies; consult the Playwright installation guidance for that environment.

Typical project files

A typical command runs the configured test suite:

npx playwright test

Write a Playwright Test Example

Suppose a demo shop has a sign-in page and a dashboard that displays a welcome message. A concise test can verify the essential journey. The selectors below assume the application exposes accessible labels and headings; adapt the URL and expected text to your own app.

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

test('user can sign in', async ({ page }) => {
  await page.goto('http://localhost:3000/login');

  await page.getByLabel('Email').fill('alex@example.com');
  await page.getByLabel('Password').fill('example-password');
  await page.getByRole('button', { name: 'Sign in' }).click();

  await expect(page).toHaveURL(/dashboard/);
  await expect(
    page.getByRole('heading', { name: 'Welcome, Alex' })
  ).toBeVisible();
});

Playwright Test provides the page fixture for each test. It opens a page in an isolated browser context, helping prevent cookies and local storage from leaking between tests. The expect assertions retry for a period while waiting for the expected condition, so you generally do not need to add arbitrary sleeps.

Prefer user-facing locators

Locators describe how a user or assistive technology identifies an element. They are usually more robust than selectors tied to layout or implementation details.

Avoid brittle selectors such as div:nth-child(3) > button. Minor markup or styling changes can break them without changing the user experience. If a locator matches multiple elements unexpectedly, make it more specific rather than relying on a positional choice that may become stale.

Configure Browsers and Test Runs

Playwright Test uses projects to run the same tests with different settings, such as a browser engine or device profile. A generated configuration may already define Chromium, Firefox, and WebKit projects. Here is a simplified example:

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

export default defineConfig({
  testDir: './tests',
  retries: process.env.CI ? 2 : 0,
  reporter: process.env.CI ? 'html' : 'list',
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
});

With baseURL set, tests can use relative paths such as page.goto('/login'). Project names and device descriptors configure test runs; they do not install Google Chrome, Mozilla Firefox, or Apple Safari as branded applications. Playwright normally uses its own compatible browser builds.

Cross-browser coverage can reveal engine-specific behavior, but running every test on every browser increases execution time. Start with the browser or browsers that matter most to your users, then expand coverage for critical flows or areas with known compatibility risks. Browser choice is part of a larger configuration decision, as discussed in UC Browser – The New Browser That Can Beat Chrome, Firefox, and Opera.

Use Page Objects When They Add Clarity

A page object groups locators and actions for a page or component. It can make repeated workflows easier to maintain, especially when several tests use the same sign-in form. Keep the abstraction focused: a page object should describe useful interactions, not hide every assertion behind layers of helper methods.

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

export class LoginPage {
  readonly email: Locator;
  readonly password: Locator;
  readonly signInButton: Locator;

  constructor(private readonly page: Page) {
    this.email = page.getByLabel('Email');
    this.password = page.getByLabel('Password');
    this.signInButton = page.getByRole('button', { name: 'Sign in' });
  }

  async signIn(email: string, password: string) {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.signInButton.click();
  }

  async expectLoaded() {
    await expect(this.signInButton).toBeVisible();
  }
}

A test can now express the user journey without repeating locator details:

test('user can sign in', async ({ page }) => {
  const login = new LoginPage(page);

  await page.goto('/login');
  await login.expectLoaded();
  await login.signIn('alex@example.com', 'example-password');

  await expect(page).toHaveURL(/dashboard/);
});

Page object trade-offs

Debug Failures and Reduce Flakiness

A failing browser test can point to an application bug, a test assumption, or a problem in the test environment. Use Playwright’s reporting and debugging tools to find the cause rather than immediately increasing timeouts.

  1. Run the test alone: use npx playwright test tests/login.spec.ts to narrow the output.
  2. Open the HTML report: run npx playwright show-report after a reported run.
  3. Inspect a trace: when trace recording is enabled, the trace can show actions, page snapshots, and relevant network activity.
  4. Use the UI mode or inspector: interactive tools help step through the test and examine locators.

Common pitfalls include fixed waits such as page.waitForTimeout(3000), tests that depend on another test’s state, and shared accounts or data that can be modified concurrently. Replace fixed sleeps with assertions that express the condition you need, such as waiting for a confirmation message or URL.

Make test data predictable. Create or reset records through an API or a dedicated test setup when possible, and avoid relying on a production account. Keep secrets out of source control; provide credentials through environment variables or your CI secret store. Use retries sparingly: they can help diagnose intermittent failures in CI, but a test that passes only on retry still deserves investigation.

Choose the Right Scope for Browser Automation

End-to-end browser tests provide confidence that key parts of an application work together. However, using them for every small condition can create a slow, expensive suite. A practical balance is to test business rules with unit or API tests and reserve browser automation for a focused set of high-value user journeys.

For example, test that a discount calculation works at the unit or API layer, then use a browser test to confirm that a shopper can apply a valid discount and see the updated total. The same principle applies outside websites: automation can support complex workflows, while other technologies address different problems. For an example of automation beyond browser testing, read Computer Vision in Manufacturing – The Future of Automation Is Already Here.

Conclusion

A reliable Playwright browser automation test starts with a clear user journey, accessible and stable locators, and assertions that describe the outcome you expect. Add browser projects according to real compatibility needs, and introduce page objects when they reduce duplication without hiding test intent. Keep test data isolated, avoid fixed waits, and use traces and reports to investigate failures. With those practices in place, Playwright can provide fast, actionable feedback on the experiences that matter most to your users.

Exit mobile version