Skip to main content

Playwright

Description

Playwright is a powerful end-to-end testing framework developed by Microsoft that enables reliable cross-browser web automation. It provides a unified API to automate web browsers including Chromium, Firefox, and WebKit, making it ideal for testing web applications across different browsers and platforms.

Key Features:

  • Cross-browser support: Works with Chromium, Firefox, and WebKit
  • Multi-language support: JavaScript/TypeScript, Python, C#, and Java
  • Auto-waiting: Automatically waits for elements to be ready
  • Network interception: Mock and stub network requests
  • Mobile testing: Emulate mobile devices and viewports
  • Screenshot and video recording: Built-in visual testing capabilities
  • Parallel execution: Run tests in parallel for faster execution

Installation

Node.js (JavaScript/TypeScript)

# Install Playwright
npm install -D @playwright/test

# Install browser binaries
npx playwright install

Python

# Install Playwright
pip install playwright

# Install browser binaries
playwright install

Global Installation (Optional)

# Install globally
npm install -g @playwright/test

Basic Usage

1. Simple Test Example (JavaScript/TypeScript)

// test.js
const { test, expect } = require("@playwright/test");

test("basic test", async ({ page }) => {
// Navigate to a webpage
await page.goto("https://example.com");

// Get page title
const title = await page.title();
expect(title).toBe("Example Domain");

// Click on a link
await page.click("text=More information...");

// Take a screenshot
await page.screenshot({ path: "example.png" });
});

2. Python Example

# test_basic.py
from playwright.sync_api import sync_playwright

def test_basic():
with sync_playwright() as p:
# Launch browser
browser = p.chromium.launch(headless=False)
page = browser.new_page()

# Navigate to webpage
page.goto('https://example.com')

# Get title
title = page.title()
assert title == 'Example Domain'

# Take screenshot
page.screenshot(path='example.png')

browser.close()

3. Configuration File (playwright.config.js)

// playwright.config.js
module.exports = {
testDir: "./tests",
timeout: 30000,
expect: {
timeout: 5000,
},
use: {
headless: false,
viewport: { width: 1280, height: 720 },
screenshot: "only-on-failure",
video: "retain-on-failure",
},
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
{
name: "firefox",
use: { ...devices["Desktop Firefox"] },
},
{
name: "webkit",
use: { ...devices["Desktop Safari"] },
},
],
};

Use Cases (when/what/how)

When to use Playwright

  • End-to-end user journeys: login, checkout, onboarding, search.
  • Cross-browser regression: verify UI/behavior across Chromium, Firefox, WebKit.
  • Network-heavy apps: mock/stub APIs to make tests reliable and fast.
  • Release/CI gates: run headless in CI to block regressions.