Playwright for Beginners: Complete Step-by-Step Tutorial

Introduction: Why Learn Playwright for Beginners?

If you are starting your journey in test automation, Playwright for beginners is a strong place to start. Playwright is a modern end-to-end testing framework that lets you automate web applications across Chromium, Firefox, and WebKit.

Unlike traditional browser automation approaches, Playwright provides built-in features such as auto-waiting, web-first assertions, browser contexts, tracing, screenshots, parallel execution, and powerful locators.

For QA Automation Engineers and SDETs, learning Playwright also means learning skills that are useful in modern automation frameworks and CI/CD pipelines.

This Playwright Tutorial for Beginners starts from zero and gradually introduces practical automation concepts using Playwright TypeScript.


What Is Playwright?

Playwright is an open-source browser automation and end-to-end testing framework originally developed by Microsoft.

It supports:

  • Chromium
  • Firefox
  • WebKit
  • TypeScript
  • JavaScript
  • Python
  • Java
  • .NET/C#

For beginners, TypeScript is an excellent choice because it combines JavaScript with static typing and is widely used in modern automation projects.

A simple Playwright test looks like this:

import { test, expect } from ‘@playwright/test’;

test(‘verify Playwright website’, async ({ page }) => {

  await page.goto(‘https://playwright.dev/’);

  await expect(page).toHaveTitle(/Playwright/);

});

The test opens the website and verifies its title.


Why Learn Playwright for Automation Testing?

There are several reasons Playwright is attractive for beginners.

1. Simple syntax

Playwright tests are readable:

await page.getByRole(‘button’, { name: ‘Login’ }).click();

2. Automatic waiting

Playwright automatically waits for many actionability conditions before performing actions, reducing the need for arbitrary sleep statements.

3. Powerful locators

Playwright provides user-facing locators such as getByRole(), getByText(), getByLabel(), and getByTestId().

4. Cross-browser testing

The same test can be executed against Chromium, Firefox, and WebKit.

5. Built-in debugging

Screenshots, videos, traces, HTML reports, headed execution, and debugging tools make failed tests easier to investigate.

6. Career relevance

For QA engineers moving from Selenium to modern automation, Playwright provides useful exposure to:


Playwright vs Selenium for Beginners

Both Playwright and Selenium are valuable automation technologies.

FeaturePlaywrightSelenium
Main useWeb automation/testingWeb automation/testing
Auto-waitingBuilt inRequires more explicit handling
BrowsersChromium, Firefox, WebKitMajor browsers
LanguagesTS, JS, Python, Java, .NETJava, Python, C#, JS, etc.
TracingBuilt inUsually additional tooling
Browser contextsBuilt inDifferent architecture
Modern locatorsStrong built-in locator APIStandard locator APIs
Parallel testingBuilt into Playwright TestUsually configured through frameworks
Beginner experienceModern and conciseMature and widely documented

For someone completely new to automation, Playwright can feel easier because many synchronization problems are handled by the framework.

However, Selenium remains highly relevant because many enterprise organizations still use Selenium-based frameworks.

Career tip: Do not treat Playwright vs Selenium as an either/or decision. Understanding both can make you more flexible as a QA Automation Engineer.


Playwright Installation and Project Setup

Step 1: Install Node.js

Install a current Node.js version suitable for your development environment.

Verify installation:

node –version

npm –version

Step 2: Create a Playwright project

The easiest approach is:

npm init playwright@latest

The setup wizard asks questions such as:

Choose TypeScript for this tutorial.

You can also install Playwright Test into an existing Node project:

npm install -D @playwright/test

Then install the supported browsers:

npx playwright install

The official Playwright documentation recommends installing @playwright/test as a development dependency and provides the CLI for checking the installed version.

Check the version:

npx playwright –version


Understanding Playwright Project Structure

A typical beginner project can look like this:

playwright-project/

├── tests/

│   └── example.spec.ts

├── pages/

│   └── LoginPage.ts

├── playwright.config.ts

├── package.json

├── package-lock.json

└── test-results/

Important files include:

tests/

Contains your test cases.

pages/

Contains Page Object Model classes.

playwright.config.ts

Contains configuration such as:

  • Browsers
  • Base URL
  • Timeout
  • Retries
  • Reporter
  • Parallel execution

test-results/

Contains artifacts generated after test execution.


Writing Your First Playwright Test

What it does

The following Playwright example opens the Playwright website and checks the page title.

How it works

The page fixture represents a browser page. Playwright Test creates an isolated browser context for each test.

Code

import { test, expect } from ‘@playwright/test’;

test(‘verify Playwright homepage’, async ({ page }) => {

  await page.goto(‘https://playwright.dev/’);

  await expect(page).toHaveTitle(/Playwright/);

});

Expected result

The test passes if the page title contains Playwright.

Run it using:

npx playwright test

For a visible browser:

npx playwright test –headed

Best practice

Keep each test focused on one business behavior instead of creating one extremely large test.


Playwright Locators and Element Interaction

Locators are one of the most important concepts in a Playwright for Beginners Tutorial.

Playwright recommends prioritizing user-facing locators and explicit testing contracts.

getByRole()

Use roles for buttons, links, checkboxes, headings, and other accessible elements.

await page.getByRole(‘button’, { name: ‘Login’ }).click();

getByText()

Useful for visible non-interactive text.

await expect(page.getByText(‘Welcome’)).toBeVisible();

getByLabel()

Excellent for form fields.

await page.getByLabel(‘Username’).fill(‘admin’);

CSS locator

You can also use:

await page.locator(‘#username’).fill(‘admin’);

Test ID

For a stable application testing contract:

await page.getByTestId(‘submit-button’).click();

Best locator priority

A practical order is:

  1. getByRole()
  2. getByLabel()
  3. getByText()
  4. getByTestId()
  5. CSS selectors
  6. XPath when genuinely necessary

Avoid extremely long CSS or XPath expressions because they can become fragile when the application’s DOM changes.


Assertions and Auto-Waiting

Assertions verify whether the application behaves as expected.

await expect(page).toHaveTitle(/Playwright/);

await expect(page).toHaveURL(/playwright/);

await expect(page.getByRole(‘heading’)).toBeVisible();

Playwright provides web-first assertions that retry until the expected condition is met or the timeout is reached.

Auto-Waiting Example

await page.getByRole(‘button’, { name: ‘Submit’ }).click();

await expect(page.getByText(‘Submitted successfully’)).toBeVisible();

You normally do not need:

await page.waitForTimeout(5000);

Avoid hard-coded waits because they slow tests and can still produce flaky behavior.


Real-World Playwright Examples

Login Automation

What it does

Automates a typical login workflow.

Code

import { test, expect } from ‘@playwright/test’;

test(‘user login’, async ({ page }) => {

  await page.goto(‘https://example.com/login’);

  await page.getByLabel(‘Username’).fill(‘testuser’);

  await page.getByLabel(‘Password’).fill(‘Password123’);

  await page.getByRole(‘button’, { name: ‘Login’ }).click();

  await expect(page.getByText(‘Dashboard’)).toBeVisible();

});

Expected result

The user logs in and the Dashboard becomes visible.

Best practice

Do not hard-code real production passwords into source code. Use environment variables or secure CI/CD secrets.


Handling Forms, Dropdowns, Checkboxes, Alerts, and File Uploads

Dropdown

For a standard HTML select:

await page.getByLabel(‘Country’).selectOption(‘IN’);

Checkbox

await page.getByLabel(‘Accept Terms’).check();

Verify it:

await expect(page.getByLabel(‘Accept Terms’)).toBeChecked();

Radio button

await page.getByLabel(‘Male’).check();

File upload

await page.getByLabel(‘Upload document’)

  .setInputFiles(‘test-data/sample.pdf’);

JavaScript dialog

Playwright can handle dialogs using event listeners:

page.on(‘dialog’, async dialog => {

  console.log(dialog.message());

  await dialog.accept();

});

await page.getByRole(‘button’, { name: ‘Delete’ }).click();

For beginners, remember that alerts are browser dialogs, while HTML modal windows are usually normal DOM elements and should be handled with locators.


Working with Multiple Pages, Frames, and Popups

Multiple Pages

Suppose clicking a link opens a new tab.

const newPagePromise = page.waitForEvent(‘popup’);

await page.getByRole(‘link’, { name: ‘Open Report’ }).click();

const newPage = await newPagePromise;

await newPage.waitForLoadState();

console.log(await newPage.title());

Iframes

Use frameLocator():

const paymentFrame = page.frameLocator(‘#payment-frame’);

await paymentFrame.getByLabel(‘Card Number’).fill(‘4111111111111111’);

Frame locators can also be chained with role and other locator methods.


Playwright Page Object Model for Beginners

Page Object Model, or POM, separates test logic from page interaction logic.

Instead of writing this repeatedly:

await page.getByLabel(‘Username’).fill(‘admin’);

await page.getByLabel(‘Password’).fill(‘password’);

await page.getByRole(‘button’, { name: ‘Login’ }).click();

create a page class.

LoginPage.ts

import { Page } from ‘@playwright/test’;

export class LoginPage {

  constructor(private page: Page) {}

  username = this.page.getByLabel(‘Username’);

  password = this.page.getByLabel(‘Password’);

  loginButton = this.page.getByRole(‘button’, { name: ‘Login’ });

  async login(username: string, password: string) {

    await this.username.fill(username);

    await this.password.fill(password);

    await this.loginButton.click();

  }

}

Test

import { test, expect } from ‘@playwright/test’;

import { LoginPage } from ‘../pages/LoginPage’;

test(‘login using POM’, async ({ page }) => {

  const loginPage = new LoginPage(page);

  await page.goto(‘https://example.com/login’);

  await loginPage.login(‘testuser’, ‘Password123’);

  await expect(page.getByText(‘Dashboard’)).toBeVisible();

});

Why use POM?

It provides:

  • Reusable methods
  • Cleaner tests
  • Centralized locators
  • Easier maintenance
  • Better scalability

For enterprise automation frameworks, POM is usually combined with fixtures, test data, utilities, configuration, reporting, and CI/CD.


Fixtures, Hooks, and Test Organization

Fixtures provide reusable test dependencies.

The built-in page fixture is one example.

Hooks help organize setup and cleanup.

import { test, expect } from ‘@playwright/test’;

test.describe(‘Login Tests’, () => {

  test.beforeEach(async ({ page }) => {

    await page.goto(‘https://example.com/login’);

  });

  test(‘valid login’, async ({ page }) => {

    await page.getByLabel(‘Username’).fill(‘admin’);

    await page.getByLabel(‘Password’).fill(‘password’);

    await page.getByRole(‘button’, { name: ‘Login’ }).click();

    await expect(page.getByText(‘Dashboard’)).toBeVisible();

  });

});

Useful hooks include:

  • beforeEach
  • afterEach
  • beforeAll
  • afterAll

Playwright supports these hooks for organizing test setup and teardown.


Debugging, Screenshots, Trace Viewer, and Reports

Debugging is an essential skill for anyone learning Playwright automation testing.

Screenshot

await page.screenshot({

  path: ‘screenshots/homepage.png’,

  fullPage: true

});

Debug mode

You can run:

npx playwright test –debug

You can also use the Playwright Inspector to step through actions.

HTML report

After running tests:

npx playwright show-report

The HTML report helps identify:

Trace Viewer

Tracing is particularly useful for CI failures because it can capture detailed execution information.

A typical workflow is:

npx playwright test

Then inspect the generated trace through the Playwright tooling.

Beginner tip: When a test fails, do not immediately increase the timeout. First inspect the locator, page state, network behavior, screenshot, and trace.


Running Tests in Different Browsers and Parallel Execution

A basic configuration can define multiple projects:

import { defineConfig, devices } from ‘@playwright/test’;

export default defineConfig({

  testDir: ‘./tests’,

  projects: [

    {

      name: ‘chromium’,

      use: { …devices[‘Desktop Chrome’] },

    },

    {

      name: ‘firefox’,

      use: { …devices[‘Desktop Firefox’] },

    },

    {

      name: ‘webkit’,

      use: { …devices[‘Desktop Safari’] },

    },

  ],

});

Run a specific browser:

npx playwright test –project=chromium

Playwright Test also supports parallel execution. For large suites, parallelization can reduce execution time, but tests should remain independent.


Basic Playwright CI/CD Integration

A beginner-friendly CI/CD workflow is:

Developer pushes code

        ↓

CI pipeline starts

        ↓

Install dependencies

        ↓

Install Playwright browsers

        ↓

Run tests

        ↓

Generate report

        ↓

Publish results

For GitHub Actions, a basic workflow is:

name: Playwright Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v6

      – uses: actions/setup-node@v6

        with:

          node-version: lts/*

      – run: npm ci

      – run: npx playwright install –with-deps

      – run: npx playwright test

      – uses: actions/upload-artifact@v5

        if: ${{ !cancelled() }}

        with:

          name: playwright-report

          path: playwright-report/

Playwright’s official CI guidance recommends installing dependencies, installing browser dependencies, running the test suite, and publishing the HTML report as an artifact.


Common Beginner Mistakes and Solutions

MistakeBetter approach
Using waitForTimeout() everywhereUse locators and web-first assertions
Using fragile XPathPrefer role, label, text, or test ID
Putting everything in one testSplit tests by business behavior
Hard-coding passwordsUse environment variables/secrets
Ignoring failed tracesAnalyze screenshots and traces
Sharing state between testsKeep tests isolated
Making huge page classesKeep POM classes focused
Running only ChromiumAdd cross-browser coverage
Ignoring CIRun tests automatically
Writing unstable selectorsUse resilient locator strategies

Playwright Best Practices for Beginners

Follow these rules as your framework grows:

  1. Prefer getByRole() and other user-facing locators.
  2. Avoid unnecessary explicit waits.
  3. Use expect() for verification.
  4. Keep tests independent.
  5. Use Page Object Model for reusable workflows.
  6. Store secrets outside source code.
  7. Keep test data separate from test logic.
  8. Use meaningful test names.
  9. Capture traces for useful failure analysis.
  10. Run important tests in CI/CD.
  11. Review flaky tests instead of simply increasing timeouts.
  12. Learn TypeScript alongside Playwright.

These practices align closely with Playwright’s recommendations around resilient locators, web-first assertions, and CI usage.


Playwright Interview Questions with Answers

1. What is Playwright?

Playwright is a browser automation and end-to-end testing framework used to test modern web applications.

2. Is Playwright suitable for beginners?

Yes. Its readable API, built-in waiting, browser support, debugging features, and TypeScript integration make it suitable for beginners.

3. What is a locator in Playwright?

A locator identifies an element on a web page.

Example:

page.getByRole(‘button’, { name: ‘Login’ })

4. What is auto-waiting?

Auto-waiting means Playwright waits for required element conditions before performing actions.

5. What is Page Object Model?

POM is a design pattern that separates page interaction logic from test cases.

6. How do you run Playwright tests?

npx playwright test

7. How do you run tests in headed mode?

npx playwright test –headed

8. How do you generate an HTML report?

npx playwright show-report

9. Can Playwright run tests in parallel?

Yes. Playwright Test supports parallel execution.

10. Playwright vs Selenium for beginners: which should I learn?

Learn Playwright if you want modern browser automation with TypeScript and built-in features. Also learn Selenium if your target companies use Selenium-based frameworks.


Playwright Learning Roadmap for Beginners

A practical learning sequence is:

Level 1: Fundamentals

Learn:

Level 2: Browser Automation

Learn:

  • page.goto()
  • Click
  • Fill
  • Select
  • Check
  • Upload
  • Navigation

Level 3: Locators

Learn:

  • getByRole()
  • getByText()
  • getByLabel()
  • getByPlaceholder()
  • getByTestId()
  • CSS
  • XPath

Level 4: Assertions and Synchronization

Learn:

  • expect()
  • Web-first assertions
  • Auto-waiting
  • Timeouts
  • Dynamic elements

Level 5: Framework Design

Learn:

  • Page Object Model
  • Fixtures
  • Hooks
  • Test data
  • Utilities
  • Environment configuration

Level 6: Advanced Automation

Move into:

  • API testing
  • Authentication
  • Multiple pages
  • Frames
  • Network interception
  • Parallel execution
  • Advanced reporting

Level 7: DevOps

Learn:

  • Git
  • GitHub Actions
  • CI/CD
  • Docker
  • Test artifacts
  • Failure analysis

For career growth, combine your Playwright skills with SQL, API testing, Git, CI/CD, JavaScript/TypeScript, and software testing fundamentals.


Recommended Next Playwright Tutorials

After completing this Playwright for Beginners Tutorial, continue with related topics:

This progression takes you from basic browser automation to building a production-style Playwright automation framework for beginners and eventually an enterprise framework.


FAQs: Playwright for Beginners

What is Playwright?

Playwright is a browser automation and end-to-end testing framework for modern web applications. It supports Chromium, Firefox, and WebKit.

How do I get started with Playwright?

Install Node.js, create a project with npm init playwright@latest, select TypeScript, install the browsers, and create your first .spec.ts test.

Is Playwright suitable for beginners?

Yes. Beginners can start with basic navigation and locators before progressing to assertions, Page Object Model, fixtures, reporting, and CI/CD.

Is Playwright free to use?

Yes. Playwright is an open-source framework.

What language is best for Playwright beginners?

TypeScript is a strong choice for beginners who want to build modern automation frameworks. JavaScript, Python, Java, and .NET are also supported.

Is Playwright better than Selenium for beginners?

Neither tool is universally better. Playwright offers modern built-in capabilities, while Selenium has a very mature ecosystem and extensive enterprise adoption.

Does Playwright require coding?

Yes. Playwright automation requires programming. Beginners should learn basic TypeScript or JavaScript along with testing concepts.

Can Playwright be used for API testing?

Yes. Playwright Test also supports API testing, allowing teams to validate APIs alongside UI workflows.

Can Playwright run in CI/CD?

Yes. Playwright can run in CI environments such as GitHub Actions and other CI providers.

What should I learn before Playwright?

Learn basic software testing concepts, HTML, CSS selectors, JavaScript or TypeScript fundamentals, HTTP/API basics, and Git.

Leave a Comment

Your email address will not be published. Required fields are marked *