Playwright Basics
Install Playwright, write your first script, and understand browsers, contexts, and pages.
Installation
Install @playwright/test and run npx playwright install to download browser binaries (Chromium, Firefox, WebKit). Playwright bundles consistent browser versions across OS for reproducible CI.
Init project with npx playwright init for example config, tests folder, and GitHub Actions workflow template.
npm init playwright@latest
// playwright.config.ts
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: { baseURL: "http://localhost:3000" },
});First Script
Tests import test and expect from @playwright/test. test block receives fixtures including page—a isolated tab in browser context. await page.goto navigates; await expect asserts with auto-waiting.
Playwright is async throughout—always await page actions and assertions.
import { test, expect } from "@playwright/test";
test("homepage has title", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveTitle(/Quality Sites/);
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
});Browser Context
Browser contexts isolate cookies, storage, and permissions—like incognito profiles. Each test typically gets fresh context preventing state leakage.
Configure viewport, locale, timezone, geolocation, and color scheme per context in config use options or test fixtures.
- browser.newContext() in library mode for custom automation scripts
- storageState reuses authenticated session across tests
- Multiple contexts in one browser enable multi-user scenarios
test.use({
viewport: { width: 1280, height: 720 },
locale: "en-US",
timezoneId: "America/New_York",
});Pages and Locators
page provides navigation, locators, and events. Prefer getByRole, getByLabel, getByText over CSS selectors— resilient and accessibility-aligned.
Locators auto-wait and retry until action or assertion timeout—reduces manual wait boilerplate.
await page.getByLabel("Email").fill("ada@example.com");
await page.getByRole("button", { name: "Sign in" }).click();Running Tests
npx playwright test runs headless by default. --headed shows browser; --ui opens interactive UI mode. --debug opens inspector with step-through.
Report list, html, json, junit available—html report excellent for local failure review.
npx playwright test npx playwright test tests/login.spec.ts --project=chromium npx playwright show-report