Testleaf

Free Playwright Tutorial on Assertions and Validations for Automation Testers

Assertions and Validations in Playwright

 

Introduction

In automation testing, running scripts isn’t enough—you need to validate what happens after each action. That’s where assertions come in. Without them, your tests might pass even if your app is broken.

Playwright, one of today’s most powerful end-to-end testing frameworks, makes assertions simple and powerful through its built-in expect() API. With features like:

  • Auto-waiting for elements

  • Soft assertions

  • Clear, developer-friendly error reporting

…you can write tests that don’t just run—they verify your app works exactly as expected.

In this free Playwright tutorial on assertions and validations, we’ll explore:

  • How Playwright’s expect() works

  • The most useful assertion methods

  • Best practices for writing reliable, bug-catching tests.

Why Are Assertions Crucial in Automation Testing?

Think of assertions as the truth detectors in your test scripts. They check whether the application actually behaves the way it should—after every action.

Without assertions, a test may “pass” even when your login fails or a button doesn’t work. That’s not just risky—it defeats the purpose of automation.

This is where Playwright’s expect() API steps in. It:

  • Automatically waits for elements or values to meet the condition

  • Helps you write flaky-free tests without relying on sleep() or wait()

  • Makes validation cleaner, faster, and more reliable

In short: Assertions aren’t optional—they’re what make test automation meaningful.

What is expect() in Playwright?

In Playwright, expect() is the built-in assertion function (imported from @playwright/test) that verifies if a condition is met.

What makes it powerful? It waits automatically until the condition becomes true or the timeout expires—so your tests aren’t dependent on fragile sleep() calls.

import { test, expect } from '@playwright/test';
await expect(locator).toBeVisible();

This approach ensures:

  • More stable tests

  • Less flakiness

  • Cleaner, readable code without manual waits

With expect(), Playwright turns asynchronous UIs into predictable testing flows.

Common Assertions in Playwright (with Code Examples)

Playwright’s expect() API comes with several built-in matchers that help validate your application’s behavior. Here are some of the most commonly used assertions every automation tester should know:

1. toBeVisible(): 

Checks if an element is visible in the DOM.

await expect(locator).toBeVisible();

Use this to confirm buttons, modals, or alerts are shown when expected.

2. toBeHidden():

Validates that an element is either hidden or not in the DOM.

await expect(locator).toBeHidden()

Useful for checking if a loader or popup disappears after an action.

Playwright automation testing

3. toHaveText(text):

Ensures the element’s text matches exactly (string or regex).

await expect(locator).toHaveText(‘Welcome’);

Perfect for validating headers, error messages, or button labels.

Popular Articles: Infosys interview questions for automation testing

4. toContainText(text):

Verifies that the element’s text contains a substring.

await expect(locator).toContainText(‘Success’);

Ideal when text may include dynamic values (e.g., “Welcome, John!”).

5. toHaveAttribute(attr, value):

Checks if an element has a specific attribute value.

await expect(locator).toHaveAttribute(‘type’, ’email’);

Great for validating form input types or ARIA roles.

6. toHaveCount(n):

Asserts that a locator matches exactly `n` elements.

await expect(locator).toHaveCount(3);

Useful when checking list items, table rows, or repeated components.

Selenium training in chennai
7. toHaveClass(class):

Validates that an element has the specified CSS class.

await expect(locator).toHaveClass(/active/);

Works with exact match or regex—ideal for dynamic UI state validation.

Related Posts: TestLeaf’s Playwright JavaScript Course Online

8. toHaveValue(value):

Ensures an input field contains the expected value.

await expect(locator).toHaveValue(‘testuser’);

Essential for form field validations after autofill, typing, or selecting options.

These assertions are the building blocks of trustworthy automation. Mastering them ensures your tests not only perform actions but validate real outcomes—the true goal of test automation.

Built-in Auto-Waiting: No More sleep() Hacks

One of Playwright’s biggest strengths is its auto-waiting mechanism.

Whenever you use expect(), Playwright automatically waits for the condition to become true within a default timeout (5 seconds). This means you don’t need to sprinkle sleep(3000) or waitForTimeout() all over your tests.

await expect(locator).toBeVisible();

If the element isn’t visible yet, Playwright will wait up to 5 seconds before failing the test. This leads to:

  • More stable test results

  • Less flakiness from slow-loading UIs

  • Cleaner code with fewer manual wait statements.

You can adjust the waiting time if needed:

await expect(locator).toBeVisible({ timeout: 10000 }); // waits up to 10 seconds

This is especially useful for pages with heavy JavaScript or dynamic data loading.

Bottom line? Auto-waiting makes your tests smarter, more predictable, and easier to maintain.

 

Soft Assertions in Playwright: Check More, Fail Smarter

In most test cases, if an assertion fails, the test stops immediately.
But what if you want to validate multiple fields or conditions, and see all the failures together?

That’s where soft assertions come in.

What is a Soft Assertion?

A soft assertion lets the test continue running even if one of the checks fails.
It’s perfect for scenarios like:

  • Validating all fields on a form

  • Checking multiple UI components after an action

  • Comparing several values in a dashboard

Example:

await expect.soft(locator1).toHaveText(‘Welcome’);
await expect.soft(locator2).toBeVisible();
await expect.soft(locator3).toHaveValue(‘John’);

Instead of stopping at the first failure, Playwright will collect all the assertion results and report them at the end of the test.

Tip:

You can mix expect() and expect.soft() in the same test if needed.

Soft assertions help you get a full picture of what’s broken, especially during regression testing or UI reviews.

Online Classes

Assertion Failure Reporting in Playwright:

When an assertion fails in most test frameworks, you’re often left guessing what went wrong.
But with Playwright, failed assertions come with rich debugging data that speeds up root cause analysis.

Here’s What You Get with Every Failed Assertion:

  • Clear error messages
    Shows exactly what was expected vs. what was received.
    Example:
    "Expected: 'Welcome', Received: 'Welcom'"

  • DOM snapshots
    Captures the state of the DOM at the time of failure—so you can spot layout issues, missing elements, or wrong values.

  • Optional screenshots
    Automatically or manually capture visual evidence of the failed state. Super helpful for flaky or visual bugs.

Why It Matters:

This level of detail makes Playwright a favorite among automation testers. You spend less time debugging, and more time building stable tests

Pro Tip: Pair failure reporting with tools like Playwright Trace Viewer to visually step through your tests and spot the failure path.

Conclusion

Automation is more than just clicking buttons and filling forms—real testing means verifying outcomes.
With Playwright’s powerful expect() API, you can write tests that are:

  • Reliable (thanks to auto-waiting)

  • Maintainable (clear syntax, less flakiness)

  • Insightful (detailed failure reports)

From basic checks like toBeVisible() to soft assertions and detailed failure reporting, Playwright gives you all the tools you need to ensure your application works exactly as intended.

Want to go beyond tutorials?

At TestLeaf, we help automation testers master Playwright through real-time projects, mentor support, and GenAI-powered workflows.

👉 Start your journey here: TestLeaf’s Playwright Course.

We Also Provide Training In:
Author’s Bio:

Dilip

As a Senior SDET, I’m passionate about advancing the field of test automation by equipping teams with real-time solutions and high-impact frameworks. With over 8 years of experience in software testing and development, I specialize in building scalable automation platforms that ensure quality at speed. I’m committed to mentoring aspiring engineers and driving innovation through continuous learning and technical excellence. Let’s shape the future of quality engineering—together.

Dilipkumar Rajendran
Senior SDET | Playwright & Selenium Expert

linkedin

Accelerate Your Salary with Expert-Level Selenium Training

X