๐ŸŽญ Playwright 8-Tier Complete Mastery Tutorial

From zero to hero: Fundamentals โ†’ Core API โ†’ Test Structure โ†’ Advanced Interactions โ†’ Debugging โ†’ CI/CD โ†’ Visual Testing โ†’ Enterprise Mastery

๐ŸŽญ
TIER 1 โ€ข Fundamentals
Playwright Introduction
Modern Web Automation by Microsoft | TechWorld Labs

The fastest, most reliable web automation framework. Master Playwright for testing, scraping, and automation.

Tutorial
Programs
Interview Q&A

What is Playwright?

Playwright is a Node.js library developed by Microsoft that automates Chromium, Firefox, and WebKit browsers. It provides a single, powerful API for cross-browser automation, testing, scraping, and interaction.

Why Playwright?

  • Multi-browser: Chromium, Firefox, WebKit with one API
  • Fast: Direct browser automation (not remote protocol) โ€” 2-3x faster than Selenium
  • Auto-wait: Built-in waiting for elements โ€” no manual sleep() calls
  • Network control: Mock APIs, intercept requests, record HAR files
  • Visual testing: Screenshot comparison, baseline management, masking
  • Debugging: Trace Viewer, UI Mode, Inspector, Codegen
  • CI-native: Parallel execution, sharding, Docker support
  • Multi-language: TypeScript, JavaScript, Python, C#, Java

Playwright vs Selenium vs Cypress

FeaturePlaywrightSeleniumCypress
BrowsersChromium, Firefox, WebKitAllChrome, Firefox, Edge
LanguagesTS, JS, Python, C#, JavaMostJS/TS only
Speedโšกโšกโšก Fastestโšก Moderateโšกโšก Fast
Auto-waitโœ… Built-inโŒ Manualโœ… Built-in
Network Mockโœ… Fullโš ๏ธ Limitedโœ… cy.intercept()
Visual Testingโœ… NativeโŒ NoโŒ No
Setupnpm initMaven/Gradlenpm install
โœ…
Playwright is the future: Used by Google, Microsoft, Meta, and thousands of companies for production test automation.

Your First Playwright Test

TYPESCRIPT โ€” example.spec.ts
import { test, expect } from '@playwright/test';

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

Interview Questions

Q1

What is Playwright?

A modern web automation library by Microsoft that automates Chromium, Firefox, and WebKit browsers with a single API. Used for testing, scraping, and browser automation.

Q2

Why is Playwright faster than Selenium?

Playwright uses direct browser automation (Chrome DevTools Protocol), not remote protocols. No network round-trips for each action = 2-3x faster.

๐Ÿ“
TIER 1 โ€ข Fundamentals
JavaScript & TypeScript Essentials
Async/await, promises, arrow functions | TechWorld Labs

Essential JS/TS concepts for Playwright testing.

Tutorial
Programs

Async/Await (Critical)

Playwright is asynchronous. Browser operations (navigate, click, wait) happen off the main thread. Use async/await to wait for them to complete.

Arrow Functions

Playwright uses arrow functions extensively for test callbacks and fixtures.

TypeScript (Recommended)

TypeScript provides IDE autocomplete, type checking, and catches errors before running tests. Highly recommended for Playwright projects.

๐Ÿ’ก
Best practice: Always use TypeScript with Playwright. The developer experience is dramatically better.
TYPESCRIPT โ€” async/await
// โœ… Correct: async/await
test('login', async ({ page }) => {
  await page.goto('https://example.com/login');
  await page.fill('input[name="email"]', 'user@test.com');
  await page.click('.submit-btn');
});

// โŒ Wrong: missing await
test('login', async ({ page }) => {
  page.goto('...'); // Doesn't wait!
});
๐ŸŒณ
TIER 1 โ€ข Fundamentals
DOM & CSS Basics
HTML structure, CSS selectors, element relationships | TechWorld Labs

Understanding DOM and CSS is essential for writing effective locators.

Tutorial
Programs

What is the DOM?

The DOM (Document Object Model) is the in-memory tree representation of an HTML page. Playwright interacts with the DOM to find elements, read text, and trigger events.

CSS Selectors

SelectorExampleMatches
.class.btn-primaryElements with class="btn-primary"
#id#submit-btnElement with id="submit-btn"
elementbuttonAll <button> elements
[attr="value"][type="submit"]Elements with type="submit"
parent > childform > buttonDirect button children of form
๐Ÿ’ก
Best practice: Use semantic selectors (getByRole, getByLabel) first. CSS/XPath are fallbacks when semantic locators don't work.
HTML
<form>
  <label>Email</label>
  <input name="email" type="email" />
  <button type="submit" class="btn-primary">Submit</button>
</form>
๐Ÿ“ฆ
TIER 1 โ€ข Fundamentals
npm Setup & Installation
Initialize Playwright project in minutes | TechWorld Labs

Get Playwright running with a single command.

Tutorial
Programs

Prerequisites

  • Node.js 18+ (from nodejs.org)
  • npm 8+ (comes with Node.js)
  • Code editor (VSCode recommended)

Quick Start

1

Create Project

npm init playwright@latest scaffolds everything

2

Install Browsers

Automatic with setup script

3

Run Tests

npx playwright test

4

View Report

npx playwright show-report

โœ…
Zero setup: npm init handles everything โ€” config, dependencies, example tests.
BASH
# Quick start npm init playwright@latest # Run all tests npx playwright test # Run with browser visible npx playwright test --headed # Interactive UI Mode npx playwright test --ui # Debug mode npx playwright test --debug # View HTML report npx playwright show-report
๐Ÿ”ง
TIER 1 โ€ข Fundamentals
Browser DevTools Essentials
Inspect, debug, test selectors, monitor network | TechWorld Labs

Master DevTools to write better locators and understand your app.

Tutorial
Programs

Opening DevTools

  • Chrome/Edge: F12 or Cmd+Opt+I (Mac)
  • Firefox: F12 or Cmd+Opt+I (Mac)
  • Safari: Cmd+Opt+I (enable in Preferences)

Key Tabs

๐Ÿ“„
Elements
View/edit HTML and CSS. Inspect elements by hovering.
๐Ÿ’ฌ
Console
Test JavaScript. Run document.querySelector() to verify selectors.
๐ŸŒ
Network
Monitor API calls, status codes, response data.
๐Ÿ’พ
Storage
View localStorage, sessionStorage, cookies.
๐Ÿ’ก
Pro tip: Use Console to test CSS selectors before adding them to your test code. Right-click element โ†’ Copy selector.
JAVASCRIPT โ€” Testing selectors in Console
// Test CSS selector document.querySelector('.submit-btn') // Returns element or null // Find all matches document.querySelectorAll('button') // Returns NodeList // Test by role (semantic) document.querySelector('[role="button"]')
โœ…
TIER 1 โ€ข Fundamentals
Your First Playwright Test
Write and run your first E2E test | TechWorld Labs

From zero to your first working test in 5 minutes.

Tutorial
Programs

Test Anatomy

1

test() function

Define test with name and async callback

2

Fixtures

Receive page, context, browser automatically

3

Actions

Navigate, click, fill, submit

4

Assertions

Verify expected outcomes

โœ…
No setup/teardown needed: Playwright auto-creates browser context, closes it after test. Zero boilerplate.
TYPESCRIPT โ€” tests/login.spec.ts
import { test, expect } from '@playwright/test'; test('login with valid credentials', async ({ page }) => { // Navigate await page.goto('https://example.com/login'); // Fill form await page.fill('input[name="email"]', 'user@test.com'); await page.fill('input[name="password"]', 'password123'); // Submit await page.click('.btn-login'); // Assert await expect(page).toHaveURL(/dashboard/); });

Run Your Test

BASH
# Run all tests npx playwright test # Run with browser visible npx playwright test --headed # Run specific test file npx playwright test tests/login.spec.ts
๐ŸŽฏ
TIER 2 โ€ข Core API
Locators Basics
getByRole, getByText, getByLabel โ€” semantic locators | TechWorld Labs

Master modern locators that are resilient to UI changes.

Tutorial
Programs

Recommended Locators (Tier 1)

LocatorUse CaseResilience
getByRole()Buttons, links, headings โ€” semantic HTMLโญโญโญ Best
getByText()Exact visible text matchโญโญ Good
getByLabel()Form labels associated with inputsโญโญโญ Best
getByPlaceholder()Input placeholdersโญโญ Good
getByAltText()Images with alt textโญโญโญ Best
getByTestId()data-testid attributes (testing API)โญโญโญ Best
โœ…
Best practice order: (1) getByRole, (2) getByLabel, (3) getByPlaceholder, (4) getByTestId, (5) CSS/XPath only as last resort.
TYPESCRIPT โ€” locators
// By semantic role (best โ€” tests accessibility) page.getByRole('button', { name: 'Submit' }); page.getByRole('link', { name: 'Home' }); page.getByRole('heading', { level: 1 }); // By form label page.getByLabel('Email Address'); page.getByLabel('Password'); // By visible text page.getByText('Welcome'); page.getByText(/Log.* in/i); // regex // By test ID (recommended for complex apps) page.getByTestId('submit-button');
๐Ÿ”
TIER 2 โ€ข Core API
Locators Advanced
CSS selectors, XPath, complex queries | TechWorld Labs

Advanced locator techniques for complex scenarios.

Tutorial
Programs

CSS Selectors

CSS selectors are fast and readable. Use them when semantic locators don't work.

XPath

XPath is powerful for complex relationships but harder to read. Use for ancestor, preceding-sibling, complex conditions.

locator() Method

Universal locator that accepts CSS or XPath strings.

๐Ÿ’ก
Priority: Semantic (getByRole) โ†’ CSS โ†’ XPath. Never start with XPath.
TYPESCRIPT โ€” CSS & XPath
// CSS selectors page.locator('button.btn-primary'); page.locator('input[type="email"]'); page.locator('.form > button:first-child'); // XPath (for complex scenarios) page.locator('//button[@class="btn-primary"]'); page.locator('//button[text()="Submit"]');
โ›“๏ธ
TIER 2 โ€ข Core API
Chaining & Filtering
Narrow down elements with .filter(), .and(), .or() | TechWorld Labs

Combine locators for powerful element selection.

Tutorial
Programs

Locator Methods

MethodPurposeExample
.filter()Narrow by condition.filter({ hasText: 'Delete' })
.and()Both conditions must match.and(locator('[disabled]'))
.or()Either condition matches.or(locator('.alt-selector'))
.first()Get first match.first()
.last()Get last match.last()
.nth(n)Get nth match (0-indexed).nth(2)
.count()Count matchesawait .count()
โœ…
Lazy evaluation: Chained locators don't execute until you interact with them. Stale elements auto-detected.
TYPESCRIPT โ€” chaining
// Filter by text page.locator('button').filter({ hasText: 'Delete' }); // Combine conditions page.getByRole('button') .and(page.locator('[disabled]')); // Get specific match page.locator('button').nth(2); // Child element page.locator('.modal').locator('button').first();
๐Ÿ–ฑ๏ธ
TIER 2 โ€ข Core API
Page Actions
Click, fill, type, check, select, hover, drag, upload | TechWorld Labs

All actions auto-wait for element readiness.

Tutorial
Programs

Common Actions

ActionAuto-waits forExample
.click()Visibility & clickabilityawait btn.click()
.fill()Visibility & enabledawait input.fill('text')
.type()Visibility & enabledawait input.type('text')
.check()Visibility & clickableawait checkbox.check()
.selectOption()Visibility & enabledawait select.selectOption('USA')
.hover()Visibilityawait element.hover()
.dragTo()Visibility & stableawait source.dragTo(target)
.setInputFiles()Visibility & enabledawait input.setInputFiles('file.pdf')
๐Ÿ’ก
Key benefit: No manual waits. Playwright waits for element visibility, enabled state, and stable position before acting.
TYPESCRIPT โ€” actions
await page.getByRole('button', { name: 'Submit' }).click(); await page.getByLabel('Email').fill('user@example.com'); await page.locator('select').selectOption('USA'); await page.getByLabel('I Agree').check(); await page.getByLabel('Upload').setInputFiles('./document.pdf');
โœ…
TIER 2 โ€ข Core API
Assertions & Auto-wait
Web-first assertions that retry automatically | TechWorld Labs

Assertions retry by default โ€” no manual wait() calls needed.

Tutorial
Programs

Web-First Assertions

AssertionAuto-waits for (5s)Use when
toBeVisible()Element visibilityChecking element appears on screen
toHaveText()Text appearsVerifying text content
toHaveValue()Input valueForm field values change
toHaveURL()URL changesNavigation completes
toHaveTitle()Page title loadsPage fully loads
toBeChecked()Checkbox stateCheckbox is checked/unchecked
toBeEnabled()Button enabledButton is no longer disabled
toHaveCount()Element countList size reaches expected value
โœ…
Automatic retry: Assertions retry every 100ms for up to 5 seconds. Perfect for async operations.
TYPESCRIPT โ€” assertions
// Visibility (auto-waits up to 5s) await expect(page.locator('.success-msg')).toBeVisible(); // Text content await expect(page.getByRole('heading')).toHaveText('Welcome'); // URL change (navigation) await expect(page).toHaveURL(/dashboard/); // Soft assertion (doesn't fail test) await expect.soft(page.locator('.optional')).toBeVisible(); // Custom timeout await expect(element).toBeVisible({ timeout: 10000 });
โฑ๏ธ
TIER 2 โ€ข Core API
Auto-wait Concept (Why No Waits)
The superpower that eliminates flakiness | TechWorld Labs

Why Playwright's auto-wait beats manual wait() calls.

Tutorial
Programs

The Problem with Manual Waits

โŒ

Thread.sleep(2000)

Slow, brittle, wastes time. Always too short or too long.

โŒ

WebDriverWait (Selenium)

Verbose boilerplate. Doesn't cover all edge cases.

โœ…

Playwright Auto-wait

Built-in, instant, covers element + event readiness

How Auto-wait Works

When you call click(), Playwright:

  1. Waits for element visibility (not hidden by CSS, not off-screen)
  2. Waits for element to be enabled (not disabled)
  3. Waits for element to be stable (not covered by other elements)
  4. Only then performs the click
โœ…
Result: No race conditions, no flaky tests. Playwright handles all timing automatically.
TYPESCRIPT โ€” auto-wait in action
// โœ… Correct: Playwright auto-waits await page.getByRole('button').click(); // Internally waits for: visibility, enabled, stability // โŒ Wrong: Manual sleep (bad) await page.waitForTimeout(2000); // Fixed delay await page.click('button'); // Flaky, slow, unreliable // โœ… Assertions also auto-wait await expect(page).toHaveURL(/dashboard/); // Retries for 5 seconds if URL hasn't changed yet
๐Ÿช
TIER 3 โ€ข Test Structure
Hooks (beforeEach, afterEach)
Setup and teardown with test.beforeEach/afterEach | TechWorld Labs

Run code before/after each test for consistent test state.

Tutorial
Programs

Hook Types

HookWhenUse Case
beforeEach()Before each testNavigate to page, login, setup data
afterEach()After each test (always)Cleanup, logout, reset state
beforeAll()Once before all testsGlobal setup, expensive operations
afterAll()Once after all testsGlobal cleanup
โœ…
Key benefit: Hooks run in parallel for each test. No global state pollution between tests.
TYPESCRIPT โ€” hooks example
test.beforeEach(async ({ page }) => { // Setup: runs before each test await page.goto('https://example.com'); await page.fill('input[name="email"]', 'user@test.com'); }); test('dashboard loads', async ({ page }) => { // Test runs here (page already navigated) await expect(page.locator('.dashboard')).toBeVisible(); }); test.afterEach(async ({ page }) => { // Cleanup: runs after each test console.log('Test ended at: ' + page.url()); });
๐Ÿ“
TIER 3 โ€ข Test Structure
test.step() for Sub-steps
Organize complex tests into named steps | TechWorld Labs

Group related actions into labeled steps for better reports.

Tutorial
Programs

Why Steps?

  • Organize complex tests into logical phases
  • HTML report shows which step failed
  • Trace Viewer highlights steps for debugging
  • Improves readability of multi-phase flows
๐Ÿ’ก
Best practice: Use steps for complex workflows: login โ†’ navigate โ†’ perform action โ†’ verify โ†’ logout
TYPESCRIPT โ€” test.step()
test('complete e-commerce flow', async ({ page }) => { await test.step('Open homepage', async () => { await page.goto('https://example.com'); }); await test.step('Search for product', async () => { await page.fill('.search', 'laptop'); await page.click('.search-btn'); }); await test.step('Add to cart', async () => { await page.click('.add-btn'); }); });
๐Ÿ”Œ
TIER 3 โ€ข Test Structure
Fixtures & Custom Setup
Reusable test setup with built-in and custom fixtures | TechWorld Labs

The most powerful Playwright feature for test organization.

Tutorial
Programs

Built-in Fixtures

FixtureWhat it providesScope
pageBrowser tab/page for the testPer test
contextIsolated browser context (cookies, storage)Per test
browserBrowser instancePer worker
browserNamechromium, firefox, or webkitPer test

Custom Fixtures

Create fixtures for reusable setup (logged-in page, pre-populated form, API client, etc.)

โœ…
Automatic cleanup: Fixtures run in isolation. Each test gets a fresh context, no leakage between tests.
TYPESCRIPT โ€” custom fixture
import { test as base } from '@playwright/test'; const test = base.extend({ authenticatedPage: async ({ page }, use) => { // Setup: login before test await page.goto('https://example.com/login'); await page.fill('input[name="email"]', 'user@test.com'); await page.fill('input[name="password"]', 'pass'); await page.click('.login-btn'); // Use fixture in test await use(page); // Teardown: logout await page.click('.logout'); }, }); test('user dashboard', async ({ authenticatedPage }) => { await expect(authenticatedPage).toHaveURL(/dashboard/); });
๐Ÿ—๏ธ
TIER 3 โ€ข Test Structure
Page Object Model
Organize locators and page logic into reusable classes | TechWorld Labs

Maintainable test code that survives UI changes.

Tutorial
Programs

POM Principles

1

One class per page

LoginPage, DashboardPage, CheckoutPage

2

Store locators as fields

Reuse across multiple tests

3

Action methods

login(), fillForm(), submit()

4

Return objects

Enable chaining and composition

โœ…
Benefit: When UI changes, update locator in ONE place. All tests using that page auto-update.
TYPESCRIPT โ€” pages/LoginPage.ts
import { Page } from '@playwright/test'; export class LoginPage { private page: Page; constructor(page: Page) { this.page = page; } async goto() { await this.page.goto('https://example.com/login'); } async login(email: string, password: string) { await this.page.fill('input[name="email"]', email); await this.page.fill('input[name="password"]', password); await this.page.click('.submit-btn'); } } // Usage in tests test('login', async ({ page }) => { const login = new LoginPage(page); await login.goto(); await login.login('user@test.com', 'pass'); });
๐Ÿญ
TIER 3 โ€ข Test Structure
Test Data Factories
Generate consistent test data with factory functions | TechWorld Labs

Reusable functions for creating test data.

Tutorial
Programs

Why Factories?

  • Generate test users, products, orders consistently
  • Avoid hardcoded test data scattered across tests
  • Easy to create variations (premium user, guest user, admin)
  • Centralized, maintainable
๐Ÿ’ก
Pro tip: Factories work great with API testing โ€” create data via API before UI tests run.
TYPESCRIPT โ€” factories/user.factory.ts
import { faker } from '@faker-js/faker'; interface User { email: string; password: string; name: string; } export const userFactory = { create(): User { return { email: faker.internet.email(), password: 'Password123!', name: faker.person.fullName(), }; }, createAdmin(): User { return { ...userFactory.create(), email: 'admin@example.com' }; }, }; // Usage in tests test('register user', async ({ page }) => { const user = userFactory.create(); // Now use user.email, user.password, user.name });
๐Ÿท๏ธ
TIER 3 โ€ข Test Structure
Tags & Test Isolation
Organize tests with tags, control test isolation | TechWorld Labs

Run subsets of tests, ensure test independence.

Tutorial
Programs

Tags for Organization

Tag tests to run subsets: smoke tests, regression, slow tests, etc.

Test Isolation

Each test runs in isolation โ€” no state leakage. But can configure serial tests when order matters (checkout flow).

โœ…
Default behavior: Tests run parallel in isolation. Each gets fresh browser context, cookies reset.
TYPESCRIPT โ€” tags and isolation
test('login', { tag: '@smoke' }, async ({ page }) => { // This test tagged as smoke }); test.describe.serial('checkout flow', () => { test('add to cart', async ({ page }) => { // Runs first }); test('place order', async ({ page }) => { // Runs second (after previous test) }); }); // Run only smoke tests // npx playwright test --grep @smoke
๐ŸŒ
TIER 4 โ€ข Advanced Interactions
Network Interception & Mocking
Mock APIs, intercept requests, test error states | TechWorld Labs

Test without touching your backend.

Tutorial
Programs

page.route() for Network Control

page.route() intercepts HTTP requests before they leave the browser. Mock responses, abort requests, or modify headers.

Use Cases

๐ŸŽญ
Mock Responses
Return custom JSON without hitting backend
๐Ÿšซ
Abort Requests
Simulate network failures, block analytics
โš ๏ธ
Error Testing
Test 500s, 404s, timeouts instantly
๐Ÿ“ฆ
HAR Recording
Record and replay network traffic for reproducibility
โœ…
Fast error testing: Mock a 500 error instantly instead of asking backend to break themselves.
TYPESCRIPT โ€” network interception
// Mock API response await page.route('**/api/users/123', route => { route.fulfill({ status: 200, body: JSON.stringify({ id: 123, name: 'John' }), }); }); // Mock 500 error await page.route('**/api/checkout', route => { route.fulfill({ status: 500 }); }); // Abort request (network failure) await page.route('**/analytics', route => { route.abort(); }); // Wait for response const responsePromise = page.waitForResponse('**/api/login'); await page.click('.submit'); const response = await responsePromise;
๐Ÿ”Œ
TIER 4 โ€ข Advanced Interactions
API Testing & Hybrid Flows
Make HTTP requests, combine API + UI testing | TechWorld Labs

Test APIs directly, use in UI workflows.

Tutorial
Programs

APIRequestContext Fixture

Make HTTP requests (GET, POST, PUT, DELETE) directly from Playwright tests. No separate API test framework needed.

Common Patterns

  • API-first testing: Call API to get auth token, use in UI tests
  • Setup data: Create test users/orders via API before UI tests
  • Verify backend: Check API returns correct data
  • Hybrid flows: API setup + UI interaction + API verification
โœ…
Fastest approach: Setup via API (seconds) + test UI (fast) vs. manual UI setup (slow).
TYPESCRIPT โ€” API testing
test('API + UI flow', async ({ request, page }) => { // Call login API const res = await request.post('https://api.example.com/login', { data: { email: 'user@test.com', password: 'pass' } }); const { token } = await res.json(); // Use token in UI test await page.goto('https://example.com', { headers: { Authorization: `Bearer ${token}` } }); await expect(page).toHaveURL(/dashboard/); });
๐Ÿ”
TIER 4 โ€ข Advanced Interactions
State & Authentication
Reuse auth state, setup projects, handle sessions | TechWorld Labs

Skip login screens, reuse auth state across tests.

Tutorial
Programs

storageState for Auth Reuse

Save browser state (cookies, localStorage) after login. Reuse across tests to skip login flow.

Setup Projects

Playwright config supports setup projects โ€” run once before all tests to establish state.

โœ…
Performance gain: Login once, reuse auth across 100 tests. Saves minutes of total test time.
TYPESCRIPT โ€” auth setup
// First test: save auth state test('login and save state', async ({ page, context }) => { await page.goto('https://example.com/login'); await page.fill('input[name="email"]', 'user@test.com'); await page.fill('input[name="password"]', 'pass'); await page.click('.submit'); // Save storage state (cookies, localStorage) await context.storageState({ path: 'auth.json' }); }); // Other tests: reuse auth test.use({ storageState: 'auth.json' }); test('dashboard (already logged in)', async ({ page }) => { // Auth cookie already set, no login needed await page.goto('https://example.com/dashboard'); await expect(page).toHaveURL(/dashboard/); });
๐Ÿ“ฆ
TIER 4 โ€ข Advanced Interactions
iFrames & Shadow DOM
Interact with iframes and shadow DOM elements | TechWorld Labs

Handle complex DOM structures.

Tutorial
Programs

Working with iFrames

iFrames are isolated documents. Get the frame object, then interact with elements inside it.

Shadow DOM

Shadow DOM is encapsulated DOM tree. Playwright can penetrate it to find elements.

๐Ÿ’ก
Common scenario: Payment gateways (Stripe, PayPal) often use iFrames. Playwright handles them seamlessly.
TYPESCRIPT โ€” iframes and shadow DOM
// Access iframe const frameHandle = page.frameLocator('[name="payment-iframe"]'); await frameHandle.locator('input[name="card"]').fill('4111111111111111'); // Shadow DOM penetration (automatic) page.locator('input'); // Finds elements in shadow DOM too
๐Ÿ”€
TIER 4 โ€ข Advanced Interactions
Multiple Contexts & Tabs
Test multi-tab flows, user interactions | TechWorld Labs

Simulate real-world scenarios with multiple browser tabs.

Tutorial
Programs

Browser Contexts

Isolated browser sessions with separate cookies, storage, etc. Test logged-in user + guest user side-by-side.

Multiple Pages/Tabs

Open multiple pages in same context. Simulate tab switching, window focus changes.

๐Ÿ’ก
Use case: Test OAuth flows (login opens popup), account linking, multi-tab interactions.
TYPESCRIPT โ€” contexts and pages
// Multiple contexts (isolated sessions) test('user + guest comparison', async ({ browser }) => { const userContext = await browser.newContext(); const guestContext = await browser.newContext(); const userPage = await userContext.newPage(); const guestPage = await guestContext.newPage(); // Test both simultaneously await userPage.goto('https://example.com'); await guestPage.goto('https://example.com'); await userContext.close(); await guestContext.close(); }); // Multiple pages in same context const page1 = await context.newPage(); const page2 = await context.newPage(); await page1.goto('https://example.com');
๐ŸŽจ
TIER 4 โ€ข Advanced Interactions
Browser Features
Handle downloads, dialogs, emulation, geolocation | TechWorld Labs

Test advanced browser capabilities.

Tutorial
Programs

Common Browser Features

  • Downloads: Capture downloaded files without saving to disk
  • Dialogs: Handle alert/confirm/prompt dialogs
  • Geolocation: Emulate location for location-aware features
  • Device emulation: Test on iPhone, Android, tablet screens
  • Locale/timezone: Test localized features
  • Permissions: Grant/deny camera, microphone permissions
๐Ÿ’ก
Powerful: Test geolocation-based features (maps, nearby stores) without physically visiting locations.
TYPESCRIPT โ€” browser features
// Download file
const downloadPromise = page.waitForEvent('download');
await page.click('.download-btn');
const download = await downloadPromise;

// Handle dialog
page.on('dialog', dialog => {
  dialog.accept();  // or dialog.dismiss()
});

// Emulate geolocation
await context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
await context.grantPermissions(['geolocation']);
๐Ÿ”
TIER 5 โ€ข Debugging & Tools
Trace Viewer โญ The Superpower
Deep debugging: timeline, network, DOM snapshots | TechWorld Labs

The most powerful Playwright debugging tool.

Tutorial
Programs

What is Trace Viewer?

Trace Viewer records everything: DOM snapshots at each step, network requests, console logs, browser events, timestamps. Open in browser to replay test execution frame-by-frame.

What You Get

๐Ÿ“ธ
DOM Snapshots
HTML state at each step
๐ŸŒ
Network Log
All API calls, responses
๐Ÿ“Š
Timeline
Events over time
๐Ÿ–ผ๏ธ
Screenshots
Visual state at each step
โœ…
Game changer: Flaky test failed in CI but passes locally? Open trace to see exactly what happened.
TYPESCRIPT โ€” config for trace
use: { // Record trace on first retry (test failure) trace: 'on-first-retry', // or 'on', 'off' }, // View trace // npx playwright show-trace trace.zip
๐ŸŽฎ
TIER 5 โ€ข Debugging & Tools
UI Mode (Interactive Testing)
Step through tests interactively with --ui | TechWorld Labs

Run tests with a visual debugger.

Tutorial
Programs

UI Mode Features

  • Run tests with browser and UI side-by-side
  • Step through test line-by-line
  • Inspect DOM and network at each step
  • Live editing: change test code and re-run
  • Perfect for test development
โœ…
Developer favorite: Many testers use UI Mode for initial test writing, then run headless in CI.
BASH
# Launch UI Mode npx playwright test --ui # UI Mode for specific file npx playwright test tests/login.spec.ts --ui
๐Ÿค–
TIER 5 โ€ข Debugging & Tools
Codegen (Record Tests)
Generate test code by recording user actions | TechWorld Labs

Fastest way to bootstrap tests.

Tutorial

Codegen Workflow

Run npx playwright codegen to open browser + recorder. Interact with page, and Playwright generates test code automatically.

1

Start Codegen

npx playwright codegen https://example.com

2

Interact

Click, type, navigate โ€” recorder captures everything

3

Copy Code

Copy generated code into your test file

4

Refine

Add assertions, organize with POM

๐Ÿ’ก
Time saver: Codegen generates accurate selectors using semantic locators (getByRole, getByLabel).
๐Ÿ”Ž
TIER 5 โ€ข Debugging & Tools
Inspector & Debug Mode
Pause test execution, inspect state | TechWorld Labs

Step through tests with debugger.

Tutorial

--debug Mode

npx playwright test --debug pauses on first line, opens Inspector. Step through test line-by-line, see DOM/network at each step.

page.pause()

Add await page.pause() in test code to pause execution at that point. Opens Inspector for inspection.

๐Ÿ’ก
Use case: Debugging flaky test? Add page.pause() before failing step, run --debug, inspect state.
๐Ÿ“ธ
TIER 5 โ€ข Debugging & Tools
Screenshots & Video Recording
Capture test execution visually | TechWorld Labs

Record visual proof of test execution.

Tutorial

Screenshots

await page.screenshot() saves PNG to disk. Useful for documenting test state in reports.

Video Recording

Set recordVideo in config to record all test execution as MP4 video. Great for debugging, sharing test evidence.

๐Ÿ’ก
CI usage: Record video only on failure to save storage. Set recordVideo: 'retain-on-failure'.
๐Ÿ“ฆ
TIER 5 โ€ข Debugging & Tools
Artifacts (HAR, Trace, etc.)
Record and replay network traffic, traces | TechWorld Labs

Reproducible test data.

Tutorial

HAR Recording

HAR (HTTP Archive) files record all network traffic. Replay them offline to run tests without backend.

Trace Files

Trace files contain full test execution timeline: DOM snapshots, network events, console logs. Open in Trace Viewer.

โœ…
Reproducibility: Record HAR in development, replay in CI for consistent, fast tests.
โšก
TIER 5 โ€ข Debugging & Tools
Speedboard & Timeline
Performance timeline, event sequencing | TechWorld Labs

Analyze test performance.

Tutorial

Timeline Analysis

Trace Viewer shows timeline of all events: navigations, API calls, DOM updates, with exact timestamps. Identify slow operations.

๐Ÿ’ก
Optimization: See which part of test is slowest. API call taking 5s? Network mock it.
๐Ÿค–
TIER 5 โ€ข Debugging & Tools
LLM-Assisted Debugging
Use AI to analyze test failures | TechWorld Labs

Modern debugging with generative AI.

Tutorial

Using LLMs for Test Debugging

Copy test error + trace data into ChatGPT or Claude. AI can often spot issues (timing, selector specificity, logical errors) instantly.

Code Generation

Use LLMs to generate test code from requirements. "Write a test for user login flow" โ†’ instant test skeleton.

โœ…
Productivity boost: LLM + Playwright = write tests 3x faster.
โšก
TIER 6 โ€ข CI/CD & Scaling
Parallelization & Workers
Run hundreds of tests in parallel automatically | TechWorld Labs

Built-in parallel execution, no config needed.

Tutorial

Parallel by Default

Playwright runs tests in parallel automatically. Each test worker runs independently with isolated browser context. No state leakage.

Configuration

  • fullyParallel: true โ€” Enable parallelization (default)
  • workers: N โ€” Number of parallel workers (default = CPU cores)
  • CI override โ€” Set workers to 1 in CI for stability
โœ…
Speed gain: 100 tests ร— 10s each = 1000s serial, ~30s parallel on modern machine.
๐Ÿ”€
TIER 6 โ€ข CI/CD & Scaling
Sharding Across Machines
Distribute tests across CI workers | TechWorld Labs

Scale to thousands of tests in CI.

Tutorial

Sharding Concept

Divide test suite across multiple CI machines. Machine 1 runs tests 1-25, Machine 2 runs 26-50, etc. Each machine reports results, merged at end.

Usage

npx playwright test --shard=1/4 means "run shard 1 of 4 total shards"

โœ…
Scaling: 1000 tests with 10 shards = each machine runs 100 tests. Feedback in minutes, not hours.
๐Ÿ“Š
TIER 6 โ€ข CI/CD & Scaling
merge-reports Utility
Combine sharded test reports | TechWorld Labs

Unified report from parallel machines.

Tutorial

Merging Sharded Reports

After all shards complete, use npx playwright merge-reports to combine individual reports into one unified HTML report.

๐Ÿ’ก
Workflow: Shard 1-10 run tests in parallel โ†’ each uploads report to artifact storage โ†’ merge-reports combines them into one final report.
๐Ÿ™
TIER 6 โ€ข CI/CD & Scaling
GitHub Actions Setup
Run Playwright in GitHub Actions CI | TechWorld Labs

Production-ready workflow configuration.

Tutorial

Minimal Workflow

  1. Checkout code
  2. Setup Node.js
  3. Install dependencies
  4. Install Playwright browsers
  5. Run tests
  6. Upload report as artifact
โœ…
Key: Use npx playwright install --with-deps to install browser dependencies (chrome, firefox libs).
๐Ÿณ
TIER 6 โ€ข CI/CD & Scaling
Docker for Reproducibility
Run tests in consistent environment | TechWorld Labs

Guaranteed reproducible tests.

Tutorial

Official Playwright Docker Image

mcr.microsoft.com/playwright โ€” pre-installed browsers, dependencies, perfect for CI.

๐Ÿ’ก
Reproducibility guarantee: Same Docker image = same test results every time. No environment surprises.
๐Ÿ”„
TIER 6 โ€ข CI/CD & Scaling
Flakiness & Retry Strategies
Handle intermittent failures gracefully | TechWorld Labs

Make tests resilient to transient issues.

Tutorial

Built-in Retries

Configure retries for flaky tests. Playwright automatically retries failed tests (default: 0 retries, recommended: 2-3 for CI).

Common Causes of Flakiness

  • Race conditions (element appears asynchronously)
  • Network timeouts (API slow)
  • Timing-dependent tests (too strict timing)
  • Hard-coded waits (sleep()) instead of auto-wait
โœ…
Fix: Rely on Playwright's auto-wait, not manual sleep(). Use soft assertions for optional checks.
๐Ÿ“
TIER 6 โ€ข CI/CD & Scaling
Reporters (HTML, JUnit, JSON)
Generate test reports for CI integration | TechWorld Labs

Visualize results for stakeholders.

Tutorial

Available Reporters

  • HTML: Beautiful interactive report with screenshots
  • JUnit: XML format for CI system integration
  • JSON: Machine-readable format for processing
  • GitHub: Annotate PR with failures
  • Custom: Build your own reporter
๐Ÿ’ก
Best practice: Use HTML reporter locally, JUnit in CI for integration.
๐Ÿ”ง
TIER 6 โ€ข CI/CD & Scaling
Global Setup/Teardown
Run code once before/after all tests | TechWorld Labs

Setup shared resources, database initialization.

Tutorial

Global Setup Pattern

Define separate setup/teardown scripts that run once before/after entire test suite. Good for expensive operations (start test server, initialize database).

โœ…
Use case: Start backend server in setup, stop in teardown. All tests run against live server.
๐Ÿ“ธ
TIER 7 โ€ข Visual & Component
Visual Regression Testing Basics
Catch CSS regressions, layout shifts | TechWorld Labs

Detect unintended visual changes automatically.

Tutorial

Why Visual Testing?

  • Functional tests pass but UI looks broken
  • CSS changes break layout on mobile
  • Designer updates button color accidentally
  • Cross-browser rendering differences

Workflow

First run: Create baseline screenshots. Future runs: Compare pixel-by-pixel against baseline. Any difference fails test.

โœ…
Zero-config: toHaveScreenshot() just works. First run creates baseline, subsequent runs compare.
๐Ÿ“ท
TIER 7 โ€ข Visual & Component
toHaveScreenshot()
Screenshot comparison assertion | TechWorld Labs

The simplest visual regression test.

Tutorial

Basic Usage

await expect(page).toHaveScreenshot() takes screenshot and compares to baseline.

Options

  • maxDiffPixels: Allow N pixels to differ (anti-aliasing)
  • threshold: Allow X% difference (0-1)
  • mask: Ignore regions (dynamic content)
  • fullPage: Screenshot entire page
๐Ÿ’ก
Pro tip: Use maxDiffPixels for minor rendering differences, avoid threshold (too loose).
๐Ÿ“‹
TIER 7 โ€ข Visual & Component
Baseline Management
Create, update, approve baselines | TechWorld Labs

Manage visual regression baselines.

Tutorial

Baseline Workflow

  1. Create: npx playwright test on first run creates baselines
  2. Compare: Future runs compare against baselines
  3. Review: Failed tests show diff report (expected vs. actual)
  4. Approve: npx playwright test --update-snapshots accepts new baseline

Versioning

Store baselines in git alongside tests. Review baseline changes in code review โ€” visual changes require approval.

โœ…
CI safety: Baselines stored in git. Developers must deliberately commit new baselines โ€” acts as approval gate.
๐ŸŽญ
TIER 7 โ€ข Visual & Component
Masking Dynamic Regions
Ignore dynamic content in visual tests | TechWorld Labs

Hide timestamps, counters, dynamic data.

Tutorial

Why Masking?

Some content changes every test run (timestamps, random IDs, counters). Mask these regions so they don't fail visual tests.

Common Cases

  • Timestamps ("Updated 5 minutes ago")
  • Random avatars/images
  • Counters that increment
  • User-specific data
๐Ÿ’ก
Masking syntax: Pass array of regions with x, y, width, height coordinates.
๐Ÿงฉ
TIER 7 โ€ข Visual & Component
Component Testing
Test React, Vue, Angular components in isolation | TechWorld Labs

Unit testing for components with Playwright.

Tutorial

Component Testing vs E2E

Component tests: Test single component in isolation (Button, Modal, Form). E2E tests: Test full user flows.

Playwright for Components

Mount components in dev server, test with Playwright. Bridges gap between unit tests and E2E.

๐Ÿ’ก
Use case: Component library development, complex UI components that need visual regression tests.
โ™ฟ
TIER 7 โ€ข Visual & Component
Accessibility Testing
Test WCAG compliance, screen reader support | TechWorld Labs

Ensure your app is accessible to everyone.

Tutorial

Accessibility Testing with Playwright

Use getByRole() locators (encourages semantic HTML). Combine with axe-playwright for automated accessibility scanning.

Common A11y Issues

  • Missing alt text on images
  • Buttons without role/label
  • Low contrast colors
  • Missing form labels
  • Keyboard navigation broken
โœ…
Getting started: Use getByRole() in tests (ensures semantic HTML). Run axe-playwright for automated scanning.
๐Ÿ“Š
TIER 8 โ€ข Advanced Mastery
Custom Reporters & Extensions
Build custom test reporters and plugins | TechWorld Labs

Extend Playwright for your organization.

Tutorial

Custom Reporters

Implement custom reporter to send results to Jira, Slack, custom database, or build internal dashboards.

๐Ÿ’ก
Integration: Custom reporters power advanced CI workflows โ€” automatic bug filing, team notifications, trend dashboards.
โšก
TIER 8 โ€ข Advanced Mastery
Performance Testing
Test load times, measure Core Web Vitals | TechWorld Labs

Ensure your app is fast.

Tutorial

Performance Metrics

Use page.metrics() to collect: navigation time, paint time, layout time. Assert times are under budget.

Core Web Vitals

  • LCP: Largest Contentful Paint (loading speed)
  • FID: First Input Delay (interactivity)
  • CLS: Cumulative Layout Shift (visual stability)
โœ…
Continuous monitoring: Run performance tests in CI to catch regressions before production.
๐Ÿข
TIER 8 โ€ข Advanced Mastery
Enterprise Patterns
Scale testing across large organizations | TechWorld Labs

Patterns for enterprise test automation.

Tutorial

Enterprise Considerations

  • Test isolation: Parallel execution with no cross-test pollution
  • Reporting: Centralized dashboards tracking all test suites
  • Maintenance: Shared libraries, POM patterns, reusable fixtures
  • Security: Secret management, credential rotation, compliance
  • Scalability: Sharding, parallel execution, distributed infrastructure
โœ…
CoE (Center of Excellence): Many enterprises build internal Playwright frameworks with shared libraries, training, best practices.
๐Ÿ“š
TIER 8 โ€ข Advanced Mastery
Real-World Case Studies
Learn from production deployments | TechWorld Labs

Practical examples from real teams.

Tutorial

Common Patterns in Production

  • Authentication: Setup projects + storageState for multi-user testing
  • Flakiness: Use soft assertions, retries, and comprehensive tracing
  • Scale: Sharding across 10+ machines for 10,000-test suites
  • Reporting: Custom reporters sending results to Jira, Slack, internal dashboards
  • Maintenance: Shared POM library, test data factories, centralized config
โœ…
Your journey: Start with basics, gradually adopt advanced patterns as tests scale.
โ“
FAQ & Best Practices
Frequently Asked Questions & Troubleshooting
Master Common Issues & Solutions | TechWorld Labs

Resolve common Playwright challenges.

Top Interview Questions (Playwright Mastery)

Q1

What makes Playwright faster than Selenium?

Direct browser automation (Chrome DevTools Protocol) vs. remote protocol. No network latency for each action = 2-3x faster execution.

Q2

How do you handle flaky tests?

Use Playwright's auto-wait (don't use sleep()), enable retries in CI, use Trace Viewer to debug, run tests multiple times to catch intermittencies.

Q3

Explain the difference between context and page.

Page = single tab. Context = isolated session with own cookies/storage. One context can have multiple pages.

Q4

How do you test OAuth/SSO flows?

Use storageState to save auth after login, reuse across tests. Or use setup projects to login once, share state with all tests.

Q5

What's the best way to handle dynamic content in visual tests?

Use masking to ignore regions that change every run (timestamps, counters). Or use maxDiffPixels for minor anti-aliasing differences.

Q6

How do you scale tests to 1000+ suite?

Sharding across multiple CI machines (--shard flag), parallelization on each machine (workers), merge-reports to combine results.

Common Errors & Solutions

โš ๏ธ

Timeout: waiting for locator

Fix: Element not found or not visible. Use --debug to inspect, or increase timeout for slow operations.

โš ๏ธ

Strict mode: locator matched multiple elements

Fix: Make locator more specific using .first(), .last(), .nth(), or getByRole() with name/level.

โš ๏ธ

Test passes locally, fails in CI

Fix: Open Trace Viewer (trace: 'on-first-retry' in config), check for timing issues, run in docker locally.

โš ๏ธ

Browser crashes in Docker

Fix: Use official mcr.microsoft.com/playwright image. If custom, add --no-sandbox and --disable-dev-shm-usage.

Pro Tips & Best Practices

๐Ÿ’ก
Locators: Use getByRole() first. Semantic HTML makes tests resilient and promotes accessibility.
๐Ÿ’ก
Parallel testing: Embrace parallelization. Playwright isolates tests perfectly โ€” no test interference even with parallel execution.
๐Ÿ’ก
Flakiness: Never use sleep(). Use auto-wait assertions, soft assertions for optional checks, retries in CI.
๐Ÿ’ก
Debugging: Trace Viewer is your superpower. When tests fail mysteriously, open trace to see exact DOM/network state.
๐Ÿ’ก
Organization: Use POM for maintainability, fixtures for reusable setup, factories for test data generation.
๐Ÿ’ก
CI/CD: Use official Docker image, enable retries, collect artifacts (reports, traces), use sharding for scale.