Getting started with Playwright
Introduction
Playwright is an open-source automation library for web applications, developed by Microsoft and launched in January 2020. It enables developers to write scripts that automate web browsers for a wide range of tasks, including testing, web scraping, and browser-based automation workflows.
Key Features
- Cross-Browser: Playwright supports Chromium, Firefox, and WebKit.
- Cross-Platform: Works on Windows, macOS, and Linux.
- Headless & Headed Modes: Run tests in headless (for speed) or headed (for visual debugging).
- Parallel Test Execution: Supports running tests in parallel across multiple browsers and contexts, speeding up the overall test process.
- Browser Contexts: Isolated browser profiles (contexts) allow efficient testing of multiple scenarios within the same browser instance.
- Auto-Waiting: Automatically waits for elements to be actionable before performing interactions like clicks and fills, reducing flaky tests.
- Network Interception: Allows mocking of network requests, intercepting responses, and simulating network conditions for more complex testing.
- Emulation: Can emulate mobile devices, screen sizes, and geolocation, enabling testing of responsive and location-based behavior.
- Modern Web Support: Handles WebSockets, Web Workers, and Service Workers.
- Visual Comparisons: Playwright supports capturing screenshots and comparing them against baseline images for visual regression testing.
- Tracing and Debugging: Playwright provides tools for tracing test execution, recording video, and generating logs, which help in debugging and identifying issues quickly.
Playwright’s Architecture
It’s built around the following core components:
- Browser: This represents the entire browser (like Chromium, Firefox, or WebKit) running during the test. It’s the top-level entity that controls all the lower-level components.
- Browser Context: Contexts are like separate user profiles within the same browser. Each context runs as a separate session, with its own cookies, cache, and storage.
- Page: Like individual tabs or windows in the browser. Each page operates independently and can perform its own set of actions, such as navigating to URLs, clicking elements, or filling out forms.
Real Example
Here is a real test for a simple Tic Tac Toe game.
import { test, expect } from "@playwright/test";
test("Tic Tac Toe game play", async ({ page }) => {
const player1Name = "Razvan";
const player2Name = "Cosmin";
// Navigate to the game page
await page.goto("https://razvantimis.github.io/tic-tac-toe/");
// Start the game by entering player names
await page.getByLabel("Player 1's Name").fill(player1Name);
await page.getByLabel("Player 2's Name").fill(player2Name);
await page.getByRole("button", { name: "Confirm" }).click();
// Wait for the names dialog to disappear
await page.locator(".names-dialog").waitFor({ state: "hidden" });
// Helper to simulate a player move
const makeMove = async (position: number, expectedText: string) => {
const cell = page.getByTestId(`game-cell-${position}`);
await cell.click();
await expect(cell).toHaveText(expectedText);
};
// Player 1 (X) and Player 2 (O) take turns
await makeMove(0, "X");
await makeMove(1, "O");
await makeMove(3, "X");
await makeMove(4, "O");
await makeMove(6, "X"); // Winning move
// Verify the winning condition
await expect(page.locator(".result-dialog")).toBeVisible();
await expect(
page.getByRole("heading", { name: `${player1Name} Wins!` })
).toBeVisible();
});
Selecting Elements
Prefer selectors in this order: accessibility first, then stability.
page.getByRole(role, options): Targets elements by their ARIA role, enhancing accessibility in tests.
await page.getByRole("button", { name: "Confirm" }).click();
page.getByLabel(text): Targets form fields by their label, the way a user finds them.
await page.getByLabel("Player 1's Name").fill("Razvan");
page.getByTestId(testId): Using a data-testid attribute for selecting elements in tests provides stability and clarity.
await page.getByTestId(`game-cell-${position}`).click();
page.locator(selector): Selects elements using CSS selectors.
await expect(page.locator('.gamecell[data-position="0"]')).toHaveText("X");
Conclusion
Start with getByRole and getByLabel, lean on auto-waiting instead of manual sleeps, and isolate each test in its own context. Those three habits remove most flaky tests.