Playwright Masters

Playwright Automation Testing Tutorial: Install, Write and Run Your First Test

This beginner Playwright tutorial takes you through one practical goal: install Playwright Test, write a small TypeScript test, run it and understand a failure. You will use a page fixture, a locator, an action and an assertion before adding reusable framework layers.

For a tool overview, read What Is Playwright? For instructor-led practice, explore our Playwright automation testing course in Hyderabad. The later sections point to the next skills to learn after your first test works.

Table of Contents

What Is Playwright?

Playwright automates a browser so a test can perform an action and check the result. This tutorial uses Playwright Test with TypeScript. Your first goal is one independent test that you can run, explain and debug.

For features, supported languages and limitations, read What Is Playwright?. You do not need to build a reusable framework before completing this exercise.

What can Playwright test?

Playwright can help test:

  • Login pages
  • Registration forms
  • Shopping websites
  • Banking web applications
  • Dashboards
  • Search functionality
  • E-commerce checkout
  • File uploads
  • Multi-page workflows
  • APIs
  • Authentication flows
  • Responsive web applications
Playwright Automation Testing Tutorial

What Is Playwright Automation Testing?

Playwright automation testing is the process of using Playwright to automatically perform user actions and verify whether a web application works as expected.

Think of it like giving instructions to a robot tester.

For example:

Open website

↓

Click Login

↓

Enter username

↓

Enter password

↓

Click Submit

↓

Check dashboard

↓

Pass or fail

Instead of a tester repeating these steps manually every day, Playwright can execute them repeatedly.

This is especially useful for regression testing, where existing features need to be checked after new changes are introduced.

Why Use Playwright for Automation Testing?

Playwright offers powerful features that simplify and speed up modern web application testing.

1. Cross-browser testing

You can test your application against Chromium, Firefox, and WebKit.

2. Automatic waiting

Playwright waits for elements to be ready before performing actions, checking conditions such as visibility, stability, and whether an element is enabled. Its web-first assertions retry until the expected condition is met or the timeout is reached.

3. Powerful locators

You can find elements using roles, labels, text, placeholders, test IDs and other locator strategies.

4. Built-in test runner

Playwright Test provides test execution, assertions, fixtures, parallelization and reporting features.

5. API testing

You can send HTTP requests directly and combine API operations with browser tests.

6. Debugging tools

Trace Viewer, screenshots, videos and UI Mode can make failed tests easier to understand.

7. CI/CD support

Playwright can run in CI environments such as GitHub Actions and other automation pipelines.

How Does Playwright Work?

  • A simple Playwright test has three important pieces:

    Test code → Playwright → Browser

    Your test contains instructions such as:

    await page.goto('https://example.com');
    await page.getByRole('button', { name: 'Login' }).click();

    Playwright sends those instructions to the browser.

    Playwright controls the browser, performs the required actions, and verifies whether the expected results occur. 

    A useful mental model is:

    Your Test

       ↓

    Playwright Test

       ↓

    Browser Context

       ↓

    Page

       ↓

    Web Application


    A Page represents a browser tab.

    A Browser Context is an isolated browser session, similar to a fresh private browsing session.

    This isolation helps tests remain independent from one another.

Playwright Supported Browsers and Languages

Playwright officially supports:

Area

Support

Chromium

Yes

Firefox

Yes

WebKit

Yes

JavaScript

Yes

TypeScript

Yes

Python

Yes

Java

Yes

.NET

Yes

For beginners building a Playwright Test framework, TypeScript or JavaScript is a practical starting point because Playwright Test is provided in the Node.js ecosystem.

If you are completely new to programming, learn basic JavaScript concepts such as variables, functions, arrays, objects, conditions and asynchronous programming before moving deeply into Playwright.

Playwright System Requirements

Before this exercise, have Node.js, npm, a code editor and a supported operating system ready. Check compatibility in the installation guide rather than troubleshooting environment setup halfway through the test.

The goal here is one working browser test: open a page, locate an element, perform an action and verify the result.

How to Install Playwright ?

Create the exercise project with npm init playwright@latest, choose TypeScript, and allow the wizard to install browsers. If you already have a working project, continue to the first-test example below.

For setup options, version checks or failed browser downloads, use the Playwright installation guide. Return here after setup succeeds to write and understand your test.

Understanding the Playwright Project Structure

A newly created project can contain files similar to:

playwright-project/

│

├── tests/

│   └── example.spec.ts

│

├── playwright.config.ts

├── package.json

├── package-lock.json

├── playwright-report/

└── test-results/

 

tests/

This is where your test files can live.

playwright.config.ts

This is the main configuration file.

You can configure:

  • Browsers
  • Base URL
  • Retries
  • Timeouts
  • Workers
  • Reports
  • Screenshots
  • Traces

package.json

This file contains project information, dependencies and scripts.

playwright-report/

This directory can contain generated HTML report output.

test-results/

This can contain artifacts created during test execution.

Write Your First Playwright Test

Create a file such as:

tests/homepage.spec.ts

 

Add:

import { test, expect } from '@playwright/test';

test('homepage has Playwright in the title', async ({ page }) => {
  await page.goto('https://playwright.dev/');

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

 

Now run:

npx playwright test

 

Let’s understand the code.

test()

Creates a test case.

page

Represents a browser tab.

page.goto()

Navigates to a URL.

expect()

Checks whether something is true.

toHaveTitle()

Checks the page title.

This simple test teaches the basic Playwright testing cycle:

Open → Act → Verify

How to Run Playwright Tests

Save the example as tests/homepage.spec.ts. From the project folder, run that file first:

npx playwright test tests/homepage.spec.ts

Expected result: the title assertion passes for each configured browser project. If several results appear, check the projects in your configuration; they are separate executions of the same test.

To watch the browser, add --headed. To inspect and rerun the test interactively, use npx playwright test --ui.

Practice a controlled failure: change /Playwright/ to /TitleThatDoesNotExist/ and run the same file. Read the expected and received values and the failing line. Restore the original assertion and confirm it passes again. This checks that your assertion detects an incorrect result.

To generate and inspect an HTML report:

npx playwright test tests/homepage.spec.ts --reporter=html
npx playwright show-report

Read the debugging guide if the browser launches but the test fails. For missing browser binaries or setup failures, use the installation troubleshooting guide.

What Are Locators in Playwright?

A locator helps Playwright identify the specific element on a webpage that you want to interact with. 

For example, suppose a page contains:

<button>Login</button>

You can write:

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

Playwright recommends user-facing locator strategies where possible because they are generally more meaningful and maintainable.

Common 

Role

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

Text

page.getByText('Welcome')

Label

page.getByLabel('Email')

Placeholder

page.getByPlaceholder('Enter email')

Test ID

page.getByTestId('login-button')

You can also use CSS or XPath when appropriate, but do not automatically choose complicated selectors when a clear user-facing locator is available.

Common Playwright Actions

Once you locate an element, you can interact with it.

Click

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

Fill

await page.getByLabel('Email').fill('test@example.com');

Press a keyboard key

await page.getByLabel('Search').press('Enter');

Check a checkbox

await page.getByLabel('Remember me').check();

Select an option

await page.getByLabel('Country').selectOption('India');

Upload a file

await page.getByLabel('Upload file').setInputFiles('resume.pdf');

 

The important idea is simple: find the element first, then perform the action.

Assertions: How Do You Verify Results?

An assertion is a check.

For example:

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

 

You can also check:

await expect(page.getByText('Welcome')).toBeVisible();

 

Or:

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

 

Common assertions include:

  • toBeVisible()
  • toBeEnabled()
  • toBeDisabled()
  • toHaveText()
  • toContainText()
  • toHaveValue()
  • toHaveAttribute()
  • toHaveCount()
  • toHaveURL()
  • toHaveTitle()

Assertions are important because clicking a button alone does not prove that the application worked.

A good test asks:

“What result should happen after this action?”

What Is Auto-Waiting in Playwright?

One of Playwright’s important features is automatic waiting.

Imagine a button takes two seconds to become enabled.

A weak automation script might say:

Wait 5 seconds

Click button

 

The problem is that five seconds is only a guess.

Playwright instead performs actionability checks before actions such as clicking. For example, it checks whether the element is visible, stable, enabled and able to receive the event.

This can make tests more reliable.

Avoid filling your tests with unnecessary:

await page.waitForTimeout(5000);

 

Use meaningful conditions and Playwright’s built-in waiting mechanisms whenever possible.

Handling Alerts, Popups, Tabs and Frames

Real websites can open dialogs, new pages and frames.

Browser dialogs

For JavaScript dialogs such as alerts:

page.on('dialog', async dialog => {
  console.log(dialog.message());
  await dialog.accept();
});

 

New tab

You can wait for a new page when clicking a link that opens another tab:

const newPagePromise = page.waitForEvent('popup');

await page.getByText('Open Report').click();

const newPage = await newPagePromise;

 

Frames

If content is inside an iframe, Playwright provides frame-related APIs to interact with it.

The important lesson is not to treat every element as if it belongs directly to the main page.

Browser Contexts and Pages

A browser can contain multiple contexts.

A context can contain multiple pages.

Think of it like this:

Browser

 ├── Context A

 │    ├── Page 1

 │    └── Page 2

 │

 └── Context B

      └── Page 1

 

Contexts provide isolation between tests.

This is useful when one test should not accidentally reuse cookies, local storage or other session information from another test.

Screenshots, Videos and Trace Viewer

When a test fails, simply seeing:

Test failed

is not always enough.

Screenshots and videos can show what the browser looked like.

Trace Viewer is even more useful for debugging complex failures.

You can run:

npx playwright test --trace on

Then inspect the generated trace.

Trace Viewer can show actions, screenshots, DOM snapshots, source locations, errors and network information.

For CI environments, tracing on the first retry or retaining traces on failures is often more practical than recording every successful test.

Debugging Playwright Tests

When a test fails, do not immediately change random lines of code.

Follow this process:

  1. Read the error message.
  2. Identify the failed line.
  3. Check whether the URL is correct.
  4. Check the locator.
  5. Check whether the expected element actually exists.
  6. Inspect the screenshot or trace.
  7. Reproduce the problem manually.
  8. Fix the actual cause.
  9. Run the test again.

You can also use:

npx playwright test --debug

 

Debugging is a skill. A strong automation tester learns to understand why a test failed rather than simply making the error disappear.

Playwright Configuration

Keep the configuration generated during installation for this first exercise. Check which folder holds tests and which browser projects will run. You do not need custom environments, authentication setup or a reporting framework to understand one test.

Once you can run and explain the example, use the reusable Playwright framework guide to centralize execution settings across a growing suite. Change one setting at a time and rerun the same test to understand its effect.

What Are Fixtures?

The page argument in async ({ page }) is a built-in fixture. Playwright Test provides an isolated browser page for the test and manages its lifecycle. Use that page in your first exercise instead of launching a second browser manually.

Custom fixtures are a later step: they help when several tests repeat the same setup or need reusable dependencies. Continue with the framework implementation guide; the fixtures guide explains setup, cleanup and scope in more detail.

Page Object Model in Playwright

Keep the first test in one file so you can see the action and expected result together. A Page Object becomes useful when the same page interactions repeat across multiple tests.

For now, identify which lines would repeat if you added a second scenario. Do not create a class just to wrap a single click. When repetition is clear, follow the framework guide to connect a Page Object to a fixture and reuse it from a test.

Data-Driven Testing

Start with one input and one expected result. After that scenario passes, try a second input and check that the expected result changes correctly. Each case should work without another test running first.

Arrays, objects and loops make this easier once you understand the basic test. See JavaScript test-data handling for language examples and the framework guide for organizing shared data and setup.

API Testing with Playwright

Browser tests and HTTP API tests exercise different layers. Complete the browser exercise first; then use the API testing guide to learn request-based checks and backend setup.

Authentication and Sessions

For your first login exercise, use a dedicated test account and verify a visible signed-in result. Keep credentials outside committed source files.

When repeated UI logins become a maintenance problem, continue with the authentication guide to learn state reuse and isolation.

Cross-Browser Testing

A web application may behave differently in different browsers.

Testing across multiple browsers helps identify compatibility issues that may be missed when testing only one browser. 

Playwright projects can be configured for:

Chromium

Firefox

WebKit

 

For example:

projects: [
  {
    name: 'chromium',
    use: { ...devices['Desktop Chrome'] }
  },
  {
    name: 'firefox',
    use: { ...devices['Desktop Firefox'] }
  },
  {
    name: 'webkit',
    use: { ...devices['Desktop Safari'] }
  }
]

 

Cross-browser testing is particularly important when your application has a wide user base.

Parallel Testing

Imagine you have 500 tests.

Playwright can run multiple tests at the same time using parallel workers, which helps reduce overall test execution time. For reliable results, tests should be designed to run independently. 

A good test should ideally be:

  • Independent
  • Repeatable
  • Isolated
  • Predictable

In CI environments, the appropriate worker strategy depends on the environment and available resources. Playwright’s CI guidance recommends conservative worker settings where stability and reproducibility are priorities.

Reports in Playwright

A test report answers questions such as:

  • Which tests passed?
  • Which tests failed?
  • How long did they take?
  • What error occurred?
  • What browser was used?

Playwright can generate an HTML report.

Use:

npx playwright show-report

 

A useful report should help a tester move quickly from:

Failure → Evidence → Root cause → Fix

CI/CD Integration

Run the exercise reliably on your own machine before introducing a pipeline. Then follow the Playwright CI/CD guide to install dependencies, run tests and retain reports in your CI environment.

Git and GitHub for Playwright Projects

Git helps you track changes in your automation code.

A beginner should understand commands such as:

git init
git add .
git commit -m "Add login tests"
git push

 

Your repository can contain:

tests/

pages/

fixtures/

utils/

playwright.config.ts

package.json

.github/

 

Do not commit:

  • Passwords
  • API tokens
  • Authentication state
  • Private credentials
  • Environment secrets

Use environment variables or your CI platform’s secret-management system for sensitive information.

A Real-World Playwright Project Structure

Your first exercise needs a test file, the generated Playwright configuration and the package files. Keep that small structure until you can explain a passing test and a failing assertion.

Move to a reusable structure when multiple tests repeat the same interactions or setup. The Playwright framework guide shows where tests, Page Objects, fixtures and test data belong. For the reasons behind those boundaries, use the architecture guide.

Common Beginner Mistakes in Playwright

Mistake 1: Using fixed waits everywhere

Avoid unnecessary:

await page.waitForTimeout(5000);

Mistake 2: Choosing fragile locators

A selector based on changing CSS classes can break easily.

Prefer meaningful locators when possible.

Mistake 3: Writing giant tests

A test that performs 50 unrelated actions becomes difficult to debug.

Keep tests focused.

Mistake 4: Sharing state between tests

Each test should work independently without relying on another test to run before it. 

Mistake 5: Ignoring failures

A test that fails every morning but is ignored is not useful automation.

Mistake 6: Hard-coding secrets

Never put real passwords or API tokens directly into source code.

Mistake 7: Learning syntax without understanding testing

Knowing click() and fill() is not enough.

You should understand:

What should be tested? Why should it be tested? What result proves the feature works?

Troubleshooting Common Playwright Problems

“Locator not found”

Check:

  • Is the page correct?
  • Is the locator correct?
  • Is the element inside an iframe?
  • Does the element appear after an action?
  • Are there multiple matching elements?

“Timeout exceeded”

Do not immediately increase the timeout.

First ask why Playwright is waiting.

The element may be:

  • Missing
  • Hidden
  • Disabled
  • Covered
  • On another page
  • Inside a frame

Browser does not launch

Try reinstalling browser binaries:

npx playwright install

 

In Linux CI environments, you may need system dependencies as well.

Test passes locally but fails in CI

Check:

  • Browser version
  • Operating system
  • Environment variables
  • Timing
  • Network access
  • Test isolation
  • Parallel execution
  • Authentication state

Use traces and reports to compare the local and CI behavior.

Playwright vs Selenium vs Cypress

These tools solve overlapping browser automation problems, but their architectures and workflows differ.

Area

Playwright

Selenium

Cypress

Chromium testing

Yes

Yes

Yes

Firefox testing

Yes

Yes

Yes

WebKit testing

Yes

Varies by setup

Limited compared with Playwright’s WebKit support

API testing

Yes

Usually through additional libraries/tools

Yes

Auto-waiting

Strong built-in model

Often requires explicit synchronization strategies

Built-in

Browser contexts

Yes

Different session model

Different model

Languages

JS/TS, Python, Java, .NET

Many languages

Primarily JavaScript/TypeScript

CI/CD

Yes

Yes

Yes

Mobile browser emulation

Yes

Yes through ecosystem/tools

Yes

The correct tool depends on the application, team skills, existing framework, browser requirements and project constraints.

Choose a testing framework based on your project’s requirements and testing needs, rather than popularity alone.

How to Become Job-Ready with Playwright

Check that you can write a test without copying it, choose a meaningful locator, explain an assertion failure and inspect a report. These are the outcomes of this introductory exercise.

Use the Playwright roadmap to plan further practice and the syllabus to review broader topic coverage.

Practical Playwright Learning Roadmap

After the first test, choose the next resource based on your goal:

Best Practices for Playwright Automation Testing

Keep these rules in mind:

  1. Prefer stable, meaningful locators.
  2. Use assertions to verify real outcomes.
  3. Avoid unnecessary fixed waits.
  4. Keep tests independent.
  5. Keep test data manageable.
  6. Use Page Object Model when it genuinely improves maintainability.
  7. Use fixtures for reusable setup.
  8. Store secrets securely.
  9. Run tests across relevant browsers.
  10. Use traces and reports to investigate failures.
  11. Keep Playwright and browser dependencies updated.
  12. Run important tests in CI.
  13. Review flaky tests instead of ignoring them.
  14. Write tests that represent real user behavior.
  15. Focus on meaningful coverage rather than simply increasing test count.

Final Takeaway

Playwright automation testing is not about memorizing hundreds of commands.

The real goal is to learn how to create reliable, readable and maintainable tests that provide useful information about a web application’s behavior.

Start small.

First understand:

Page → Locator → Action → Assertion

Then progress to:

Fixtures → POM → API Testing → Authentication → Cross-Browser Testing → Parallel Execution → Reports → CI/CD

Once these concepts become comfortable, build a real project and practice debugging failures.

That is the path from simply knowing Playwright syntax to understanding real-world Playwright automation testing.

If you want to continue learning, explore dedicated guides for Playwright installation, locators, assertions, API testing, Page Object Model, projects, syllabus and the Playwright learning roadmap.

Frequently Asked Questions About Playwright Automation Testing

What is Playwright automation testing?

Playwright automation testing uses Playwright to automatically control browsers, perform user actions and verify expected results in web applications.

Is Playwright easy for beginners?

Yes, the basic workflow is approachable: open a page, locate an element, perform an action and verify the result. Beginners should learn basic programming and software testing concepts alongside Playwright.

How do I start learning Playwright?

Start with JavaScript or TypeScript basics, install Playwright, write simple tests, learn locators and assertions, then move to POM, fixtures, API testing, debugging and CI/CD.

Which programming language is best for Playwright?

Playwright supports JavaScript/TypeScript, Python, Java and .NET. For Playwright Test, JavaScript or TypeScript is a natural choice because the Node.js version includes the Playwright Test runner and its testing ecosystem.

Is Playwright better than Selenium?

There is no universal answer. Both are widely used automation technologies. The appropriate choice depends on browser requirements, language preferences, existing infrastructure, team skills and project needs.

Can Playwright test APIs?

Yes. Playwright provides API testing capabilities that can be used to send requests, prepare application state and validate server-side results.

Can Playwright test mobile applications?

Playwright is primarily a web testing framework. It can emulate mobile browser devices and test mobile web experiences, but it is not a replacement for native mobile application automation tools.

Is Playwright free?

Playwright is an open-source project and its core software is available for use without a paid Playwright license.

How long does it take to learn Playwright?

The time depends on your programming and testing background. Someone with automation experience may learn the fundamentals quickly, while a complete beginner should allow more time to learn programming, testing concepts and framework design together.

Is Playwright good for getting an automation testing job?

Playwright is a useful automation skill, but employers generally look for more than knowledge of a single tool. Testing fundamentals, programming, API testing, Git, CI/CD, debugging and real project experience are also important.

Playwright Masters automation testing logo - White Back ground

Playwright Masters Team

Playwright Automation Testing Experts | Industry-Focused Training & Practical Learning

Playwright Masters is a dedicated automation testing training platform focused on helping learners build practical skills in Playwright automation testing. Our training covers real-world automation concepts, framework practices, coding, debugging, API testing, cross-browser testing, CI/CD, and interview preparation to help learners develop job-ready testing skills.

Scroll to Top