Skip to main content

Run Your First Playwright Test: Complete Beginner Tutorial (2026)

 

Run Your First Playwright Test: Complete Beginner Tutorial (2026)

Category: Playwright Fundamentals

Reading Time: 12 Minutes




Introduction

Congratulations! 🎉

If you've successfully installed Playwright, you're now ready for the most exciting part of your automation journey—running your first Playwright test.

Writing your first automation script is a major milestone because it introduces the core concepts you'll use throughout your automation career:

  • Browser Automation

  • Assertions

  • Locators

  • Reporting

  • Debugging

  • Test Execution

In this guide, you'll learn how to create, execute, debug, and understand your first Playwright test from scratch.

Whether you're a Manual Tester, QA Engineer, Developer, or SDET, this tutorial will help you build a solid foundation in Playwright.


What Is a Playwright Test?

A Playwright test is an automated script that performs actions inside a browser and verifies expected outcomes.

Think of it like a robot performing user actions.

Example:

Open Website
↓
Click Login Button
↓
Enter Credentials
↓
Verify Dashboard
↓
Pass or Fail

Instead of manually testing these actions every time, Playwright performs them automatically.


Why Are Automated Tests Important?

Imagine testing a website with:

  • Login functionality

  • Search functionality

  • Shopping cart

  • Payment gateway

Testing these manually every day would be slow and error-prone.

Automation testing helps:

✅ Save time

✅ Increase coverage

✅ Reduce human errors

✅ Improve software quality

✅ Speed up releases


Understanding Playwright Test Structure

Let's look at a basic Playwright test.

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

test('Homepage Validation', async ({ page }) => {

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

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

});

At first glance this may look complicated, but it's actually very simple.

Let's break it down.


Import Statement

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

This line imports two important Playwright functions.

test

Used to create test cases.

expect

Used for validations and assertions.

Without these imports, Playwright won't know how to execute your test.


Creating Your First Test Case

test('Homepage Validation', async ({ page }) => {

});

Homepage Validation

This is the test name.

A good test name should clearly explain what the test does.

Examples:

✅ Homepage Validation

✅ Login Functionality Test

✅ Search Results Verification

❌ Test1

❌ Automation Test


Understanding Page Object

async ({ page })

The page object represents a browser tab.

Using page, you can:

  • Open websites

  • Click buttons

  • Enter text

  • Read content

  • Verify elements

Think of page as your remote control for the browser.


Opening a Website

Let's navigate to a website.

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

This command:

  1. Launches browser

  2. Opens website

  3. Waits for loading

The await keyword ensures Playwright waits until navigation completes.


What Is an Assertion?

Assertions validate expected behavior.

Without assertions, automation tests become meaningless.

Example:

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

This checks:

Does the page title contain Playwright?

If yes:

PASS

If no:

FAIL

Assertions are what determine test success.


Creating Your First Test File

Inside your Playwright project:

tests

Create:

first-test.spec.ts

Add the following code:

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

test('My First Playwright Test', async ({ page }) => {

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

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

});

Save the file.

Congratulations!

You just wrote your first automation test.


Running Your First Playwright Test

Open terminal.

Execute:

npx playwright test

Playwright will:

  • Launch browser

  • Run test

  • Validate title

  • Generate report

Expected result:

Running 1 test

✓ Passed

This means your test executed successfully.


Running a Specific Test File

Large projects contain hundreds of tests.

To execute only one file:

npx playwright test first-test.spec.ts

This saves execution time during development.


Running Tests in UI Mode

One of Playwright's best features is UI Mode.

Execute:

npx playwright test --ui

Benefits:

  • Visual execution

  • Easy debugging

  • Replay functionality

  • Trace viewer integration

UI Mode is highly recommended for beginners.


Understanding Playwright Reports

After execution:

npx playwright show-report

Playwright opens a beautiful HTML report.

The report contains:

  • Pass/Fail Status

  • Execution Time

  • Browser Information

  • Errors

  • Screenshots

  • Traces

Reports help identify failures quickly.


Common Assertions

Assertions are used in almost every test.

Verify Page Title

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

Verify URL

await expect(page)
.toHaveURL('https://playwright.dev/');

Verify Text

await expect(page.locator('h1'))
.toContainText('Playwright');

Verify Visibility

await expect(page.locator('button'))
.toBeVisible();

Verify Checkbox

await expect(page.locator('#agree'))
.toBeChecked();

Understanding Auto-Waiting

One reason Playwright is so popular is Auto-Waiting.

Example:

await page.click('button');

Playwright automatically waits until:

  • Visible

  • Enabled

  • Stable

  • Ready for interaction

This dramatically reduces flaky tests.


Real World Example: Login Test

Let's build a realistic automation scenario.

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

test('Login Test', async ({ page }) => {

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

    await page.fill('#username', 'admin');

    await page.fill('#password', 'password');

    await page.click('#login');

    await expect(page)
        .toHaveURL('https://example.com/dashboard');

});

This test:

  1. Opens Login Page

  2. Enters Username

  3. Enters Password

  4. Clicks Login

  5. Verifies Dashboard

This is how real automation projects work.


Debugging Playwright Tests

Even experienced engineers face failures.

Playwright provides excellent debugging tools.


Playwright Inspector

Run:

PWDEBUG=1 npx playwright test

Features:

  • Pause Execution

  • Step Through Code

  • Inspect Elements

  • Analyze Failures


Trace Viewer

Enable tracing.

trace: 'on'

Run test.

Open report.

You'll see:

  • Screenshots

  • Network Requests

  • Click Events

  • Console Logs

  • DOM Snapshots

Trace Viewer is one of Playwright's strongest features.


Common Beginner Mistakes

Using Hard Waits

Avoid:

await page.waitForTimeout(5000);

This makes tests slower and unstable.


Weak Locators

Avoid:

page.locator('div:nth-child(3)');

Prefer:

page.getByRole('button');

Large Test Cases

One test should verify one scenario.

Smaller tests:

✅ Easier debugging

✅ Faster maintenance


Best Practices

Use Meaningful Test Names

Good:

test('User Can Login');

Bad:

test('Test1');

Keep Tests Independent

Each test should run independently.


Use Assertions Frequently

Never assume functionality works.

Always verify.


Use UI Mode During Learning

Makes debugging significantly easier.


Interview Questions

What is a Playwright Test?

An automated script that performs browser actions and validations.


What is the Purpose of expect()?

Used for assertions and validations.


What Is page?

Represents browser page instance.


How Do You Run Playwright Tests?

npx playwright test

How Do You Open Reports?

npx playwright show-report

What Is Auto-Waiting?

Playwright automatically waits for elements to become actionable.


Certification Preparation Tips

Remember these commands:

Run Tests

npx playwright test

UI Mode

npx playwright test --ui

Open Report

npx playwright show-report

Debug Mode

PWDEBUG=1 npx playwright test

These commands commonly appear in interviews and certification exams.


Frequently Asked Questions

Is Playwright Beginner Friendly?

Yes.

Its clean API and modern tooling make it one of the easiest automation frameworks to learn.


Can I Run Tests Without UI?

Yes.

Playwright supports Headless Mode.


What Is an Assertion?

A validation used to verify expected outcomes.


Can Playwright Run Multiple Tests Simultaneously?

Yes.

Playwright supports parallel execution.


Does Playwright Generate Reports Automatically?

Yes.

HTML reports are generated after execution.


Final Thoughts

Running your first Playwright test is the beginning of your automation journey.

You now understand:

  • Test Structure

  • Assertions

  • Browser Automation

  • Reports

  • Debugging

  • Best Practices

These concepts form the foundation of every Playwright framework.

As you continue learning, you'll build more advanced automation scenarios, scalable frameworks, and real-world testing solutions.


About Bugged But Happy

Bugged But Happy shares practical automation testing tutorials, Playwright guides, interview preparation resources, certification tips, and real-world QA engineering experiences.

Learning, Testing, and Growing One Bug at a Time.

🌐 https://thebuggedbuthappy.blogspot.com/

Comments

Popular posts from this blog

Selenium 5: What’s New and Why It Still Matters in 2025

Selenium 5: What’s New and Why It Still Matters in 2025 data-full-width-responsive="true"> Selenium has been the backbone of web automation testing for over a decade. From the early days of Selenium RC to WebDriver and the release of Selenium 4, it has enabled QA engineers worldwide to automate browsers reliably. But as modern frameworks like Playwright and Cypress gained attention, critics started asking: “Is Selenium dead?” In 2025, the answer is clear: Selenium is not dead — it has evolved. With the release of Selenium 5 , the project has modernized to support new browser technologies, improve stability, and remain a cornerstone of test automation strategies. 1. Introduction — Selenium’s Legacy Selenium started in 2004 as a tool to automate browsers for functional testing. Over the years: Selenium RC gave way to Selenium WebDriver. Selenium Grid enabled parallel execution at scale. Selenium 4 introduced W3C WebDriver com...

Google Anti-Gravity Thinking in Software Testing (With Real-World Examples & Tools)

Google Anti-Gravity Thinking in Software Testing A practical mindset that prepares testers to break systems the right way Software testing is often taught as a structured activity. Write test cases. Follow steps. Verify expected results. Mark Pass or Fail. This works well in training environments — but real users don’t behave this way. They don’t read requirements. They don’t follow flows. They don’t wait patiently. They click early. They click repeatedly. They lose network. They rotate screens. They refresh pages. And when this happens, many applications fail silently. That is why production bugs exist. To catch these bugs early, testers must think differently. They must think beyond rules. They must think beyond assumptions. This is where Anti-Gravity Thinking becomes powerful. What Is Anti-Gravity Thinking in Testing? Google Anti-Gravity is a visual experiment where UI elements do not stay fixed. They float. They move. They fall out of place. In...

Chaos Testing for Automation Engineers

Chaos Testing for Automation Engineers Why automation passes in CI but fails in production ⏱ Reading time: 10–12 minutes Most automation engineers have experienced this moment: All test cases are green. Pipelines are passing. Confidence is high. And then production fails. This blog explains why that happens — and how Chaos Testing , inspired by Anti-Gravity thinking, helps automation engineers test reality instead of assumptions. Why Automation Testing Often Gives False Confidence Automation scripts usually validate: Stable environments Correct inputs Predictable flows Fast responses But real systems don’t behave this way. Production systems face: Network delays Service timeouts Partial failures Unexpected user behavior Chaos Testing exists to simulate these conditions intentionally — before users experience them. What Is Chaos Testing (In Simple Terms) Chaos Testing is n...