CodeWithMMAK
Test AutomationIntermediate

A Complete Guide to Playwright Assertions: Mastering Test Reliability

Master Playwright assertions to build reliable, flake-free automation tests. Learn about auto-retries, soft assertions, polling, and custom matchers.

CodeWithMMAK
March 3, 2023
12 min

Introduction

🎯 Quick Answer

Playwright Assertions are built on the expect library and include an automatic retry mechanism to eliminate test flakiness. The most common way to use them is by passing a locator to expect(), followed by a matcher like .toBeVisible() or .toHaveText(). For example: await expect(page.locator('.submit')).toBeVisible();. Playwright will automatically wait until the condition is met or the timeout is reached.

In automated testing, an assertion is the "moment of truth." It's where you verify that the application's actual state matches your expected outcome. Playwright's assertion library is specifically designed to handle the dynamic nature of modern web apps, providing built-in waiting and powerful matching capabilities.

đź“– Key Definitions

Assertion

A statement that verifies a specific condition is true during test execution.

Auto-Retry

A feature where Playwright repeatedly checks an assertion until it passes or a timeout occurs, reducing flakiness caused by slow loading.

Matcher

A function used to compare an actual value against an expected value (e.g., toBe, toContain, toMatch).

Soft Assertion

An assertion that allows the test to continue even if it fails, reporting all failures at the end of the test.

Core Assertion Types

Playwright provides specialized matchers for different levels of the web application:

1. Locator Assertions (Most Common)

These verify the state of specific elements on the page:

  • toBeVisible(): Ensures the element is rendered and not hidden.
  • toBeEnabled(): Checks if a button or input is clickable.
  • toHaveText('Welcome'): Matches the text content of an element.
  • toBeChecked(): Verifies a checkbox or radio button is selected.

2. Page Assertions

These verify the state of the entire browser window:

  • toHaveURL('https://example.com/dashboard'): Matches the current URL.
  • toHaveTitle('Dashboard'): Matches the page's <title> tag.

3. API Assertions

Used when testing API responses directly:

  • toBeOK(): Verifies the status code is in the 200-299 range.

🚀 Step-by-Step Implementation

1

Identify the Target

Use a locator to find the element you want to verify.

Code Snippet
const loginButton = page.locator('#login-btn');
2

Write the Assertion

Use the expect function and chain a matcher.

Code Snippet
await expect(loginButton).toBeVisible();
3

Add Custom Messages (Optional)

Provide context for failure reports.

Code Snippet
await expect(loginButton, 'Login button should be visible after page load').toBeVisible();
4

Handle Negative Cases

Use the .not property to verify a condition is not true.

Code Snippet
await expect(loginButton).not.toBeDisabled();

Advanced Assertion Techniques

Soft Assertions

Useful for verifying multiple non-critical UI elements (like footer links) without stopping the whole test on the first failure.

Code Snippet
// Test continues even if this fails
await expect.soft(page.locator('.footer')).toContainText('2024');
await expect.soft(page.locator('.social-icons')).toBeVisible();

Expect Polling

Useful for verifying conditions that aren't tied to a locator, such as an API status or a database value.

Code Snippet
await expect.poll(async () => {
  const response = await page.request.get('/api/v1/status');
  return response.status();
}, {
  message: 'Wait for API to be ready',
  timeout: 10000,
}).toBe(200);

Common Errors & Best Practices

⚠️ Common Errors & Pitfalls

  • Forgetting the 'await' Keyword

    Most Playwright assertions are asynchronous. If you omit await, the assertion might never execute, or the test might finish prematurely.

  • Using Generic Matchers for Locators

    Avoid using expect(await locator.isVisible()).toBe(true). This bypasses the auto-retry mechanism. Instead, use await expect(locator).toBeVisible().

  • Timeout Failures

    If an assertion fails due to a timeout, it often means the element is taking too long to load or the locator is incorrect. Don't just increase the timeout; investigate the root cause.

âś… Best Practices

  • âś”
    Always prefer Locator Assertions over generic ones to take advantage of Playwright's built-in retries.
  • âś”
    Use Soft Assertions sparingly. They are great for UI layout checks but shouldn't be used for critical functional paths.
  • âś”
    Keep your Assertion Messages descriptive. This saves time when debugging failed CI builds.
  • âś”
    Group related assertions using test.step to make your HTML reports more readable and organized.

Frequently Asked Questions

What is the default timeout for assertions?

By default, Playwright assertions wait for 5 seconds (5000ms) before failing.

Can I create custom matchers?

Yes, you can extend the expect library to create domain-specific matchers for your application.

Do assertions work with iframes?

Yes, you can use locators to target elements inside iframes and perform assertions normally.

Conclusion

Mastering Playwright assertions is the key to writing stable, meaningful automation. By leveraging auto-retries, specialized matchers, and advanced techniques like polling, you can create a test suite that is both powerful and resilient to the minor fluctuations of the web.

📝 Summary & Key Takeaways

Playwright assertions provide a robust framework for verifying application state with built-in flakiness protection. By using specialized locator matchers, developers benefit from automatic retries and clearer failure messages. Advanced features like soft assertions allow for comprehensive UI checks without premature test termination, while polling enables verification of non-DOM conditions. Adhering to best practices—such as always using await, preferring locator-specific matchers, and providing descriptive error messages—ensures that your automation suite remains a reliable source of truth for your software's quality.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!