Playwright Testing Guide: Writing, Running, and Optimizing Automated Tests

Last updated on: February 25, 2025

Notesly Team

School Student

Share :

1. Introduction

Overview of Automated Testing and Playwright’s Role

  1. Automated Testing:
  2. The practice of using scripts to execute tests automatically, replacing repetitive manual checks. Ensures faster feedback, consistency, and scalability.
  3. Playwright’s Role:
  4. A modern framework for end-to-end testing of web apps. Supports multiple browsers (Chromium, Firefox, WebKit), languages (JavaScript, Python, .NET), and platforms.

Key Concepts

  1. Test Scripts: Code that automates user interactions (e.g., clicking buttons).
  2. Actions: Simulated user behaviors (e.g., click(), type()).
  3. Assertions: Validations to check outcomes (e.g., expect(page).toHaveTitle(...)).
  4. Test Isolation: Ensuring tests run independently to prevent interference.

2. Writing Your First Test

Setting Up a Basic Test File

  1. Create a test file (e.g., example.spec.ts).
  2. Import Playwright:


import { test, expect } from '@playwright/test';
  1. Write a test block:


test('My first test', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Example Domain');
});

Anatomy of a Playwright Test

  1. Test Block: test('description', callback) defines a test case.
  2. Descriptions: Use clear names like 'Verify login functionality'.

Running the Test and Interpreting Results

  1. Run tests:
npx playwright test

3. Working with Actions and Interactions

Actions Overview

  1. Common Actions:

await page.click('#submit-button'); // Click
await page.fill('#email', 'user@test.com'); // Type text
await page.hover('.menu-item'); // Hover

Navigation

  1. Navigate to a URL:


await page.goto('https://example.com/login');
  1. Reload:


await page.reload();
  1. Handle Redirects: Playwright automatically follows redirects.

Interactions

  1. Forms:


await page.selectOption('#country', 'India'); // Dropdown
await page.check('#terms-checkbox'); // Checkbox
  1. Dynamic Elements:
  2. Use page.waitForSelector() to handle elements that load asynchronously.

Basic Actions

  1. Keyboard Shortcuts:


await page.keyboard.press('Enter');
  1. File Uploads:


await page.setInputFiles('#file-upload', 'path/to/file.pdf');
  1. Drag-and-Drop:


await page.dragAndDrop('#source-element', '#target-element');

4. Assertions in Playwright

Validating Outcomes with expect

  1. Common Assertions:


await expect(page).toHaveTitle('Dashboard');
await expect(page.locator('.status')).toHaveText('Success');
await expect(page).toHaveURL(/\/dashboard/); // Regex match

Custom Assertions and Retry Logic

  1. Retry Logic:


await expect(async () => {
expect(await page.innerText('.status')).toBe('Loaded');
}).toPass({ timeout: 5000 }); // Retry for 5 seconds
  1. Soft Assertions:


expect.soft(await page.textContent('#error')).toBeNull(); // Continue on failure

5. Test Isolation

Importance of Isolated Tests

  1. Prevents flaky tests caused by shared state.
  2. Ensures reliability in parallel execution.

Playwright’s Built-In Isolation

  1. Each test runs in a new browser context (separate cookies, storage).
  2. Configured via test.use():


test.use({ storageState: 'admin-auth.json' }); // Isolated auth state

Avoiding State Leakage

  1. Never use global variables to store test data.
  2. Reset databases or APIs before/after tests if needed.

6. Using Test Hooks

Setup and Teardown Workflows

  1. Global Setup (Once per Test Suite):


test.beforeAll(async () => {
await startMockServer(); // Start a server
});
  1. Per-Test Setup (Before Each Test):


test.beforeEach(async ({ page }) => {
await page.goto('/login');
await page.fill('#username', 'testuser');
await page.click('#login');
});

Sharing Context Between Tests

  1. Use fixtures to share resources (e.g., authenticated sessions).

Best Practices for Reusable Configurations

  1. Centralize common setups in a base-test.ts file.
  2. Use test.describe() to group tests with shared hooks.

7. Conclusion

Recap of Core Concepts

  1. Playwright simplifies testing with cross-browser support and intuitive APIs.
  2. Key skills: writing actions, assertions, and isolated tests.

Addinational

  1. Scaling Tests: Parallel execution, sharding.
  2. CI/CD Integration: Run tests in GitHub Actions, Jenkins.
  3. Advanced Features: API testing, visual regression, mobile emulation.