| | |

Playwright 07 ๐ŸŽญ Assertions โ€” toBeVisible, toHaveTitle, toContainText, and Retry Logic

โฑ๏ธ Estimated read: 9 min | |

Playwright’s expect is two assertion libraries in one import. The generic matchers (toBe, toEqual, toContain) work on values and read once, the same as Vitest or Jest. The web-first matchers (toBeVisible, toHaveTitle, toContainText, and the rest) work on locators and pages, and they retry until the condition passes or the timeout expires. The distinction is the one that determines whether a test is flaky: a value assertion on data that loads asynchronously fails intermittently, and the web-first assertion waits for the condition without a hard-coded delay.

This chapter covers the three most-used web-first matchers, the retry model they share, and the matchers that assert on the page rather than a single element. The sections that follow walk through the visibility assertion, the title and text assertions, and the retry configuration that sets how long an assertion waits.

Key point: Web-first matchers retry the assertion on a locator or page until it passes or the timeout expires; value matchers read once and fail immediately, so any assertion on DOM content that loads asynchronously must use the web-first form.


a. toBeVisible and the visibility model

expect(locator).toBeVisible() waits for the element to be attached to the DOM, to have a non-empty bounding box, and to not be visibility: hidden. It is the assertion for “the element is on the page and the user can see it,” and it retries until the condition passes.

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

test("shows the success message", async ({ page }) => {
  await page.goto("/checkout");
  await page.getByRole("button", { name: "Pay" }).click();

  // Retries until the message is attached and visible
  await expect(page.getByText("Payment successful")).toBeVisible();
});

The visibility model has three states, and the matchers map to them. An element that is not in the DOM is neither visible nor hidden. An element with display: none or visibility: hidden is hidden. An element with opacity: 0 is visible by Playwright’s definition, because it has a bounding box; the visible matcher is about layout, not paint.

// The element is not in the DOM yet: the assertion retries
await expect(page.getByText("Saved")).toBeVisible();

// The element is attached but hidden: toBeHidden passes
await expect(page.getByText("Loading")).toBeHidden();

// The element exists and is visible
await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();

The toBeHidden() matcher is the negation of the visibility check, and it passes when the element is detached, hidden, or not yet in the DOM. It is the correct way to wait for a loading spinner to disappear, because the spinner may be removed from the DOM rather than hidden, and toBeHidden covers both.


b. toHaveTitle and toContainText

expect(page).toHaveTitle(expected) asserts on the page’s title. The expected value can be a string for an exact match or a regular expression for a pattern match. It retries until the title matches, which is useful when the title is set by client-side code after the initial render.

// Exact match
await expect(page).toHaveTitle("Dashboard | My App");

// Regex match
await expect(page).toHaveTitle(/Dashboard/);

expect(locator).toContainText(expected) asserts that the element’s text content contains the expected substring. It is the partial match, and it retries. The exact-match variant is toHaveText, which compares the full normalized text of the element.

// Partial match: retries until the text contains "Payment"
await expect(page.getByRole("status")).toContainText("Payment");

// Exact match: retries until the full text is "Payment successful"
await expect(page.getByRole("status")).toHaveText("Payment successful");

// Array form: exact match against multiple elements
await expect(page.getByRole("listitem")).toHaveText(["One", "Two", "Three"]);

The text normalization is the detail that matters. Playwright trims whitespace and collapses internal runs of whitespace before comparing, so an element whose text is "Payment successful" matches "Payment successful". The useInnerText option changes the source from textContent to innerText, which respects the rendered layout and hides text that is not visible.


c. The retry model and the timeout

Every web-first assertion retries until it passes or the timeout expires. The default timeout is 5 seconds, set by the expect.timeout configuration option. The timeout can be set per assertion as the last argument.

// Per-assertion timeout
await expect(page.getByText("Report ready")).toBeVisible({ timeout: 30_000 });

The retry is not a fixed interval. Playwright re-evaluates the condition as the page changes, using a polling interval that is not exposed as a configuration option. The assertion stops retrying as soon as the condition passes, which is why a fast page does not wait for the full timeout.

The expect.configure({ timeout }) call creates a pre-configured expect with a different default. The expect.soft() variant records a failure without stopping the test, which is useful for asserting on several elements in one test and seeing all the failures at once.

// Pre-configured expect
const slowExpect = expect.configure({ timeout: 30_000 });
await slowExpect(page.getByText("Report")).toBeVisible();

// Soft assertion: records the failure, continues
await expect.soft(page.getByText("Header")).toBeVisible();
await expect.soft(page.getByText("Footer")).toBeVisible();

The difference between a web-first assertion and a value assertion is the retry. expect(await page.title()).toBe("Dashboard") reads the title once and fails immediately if the title is not yet set. expect(page).toHaveTitle("Dashboard") retries until the title is “Dashboard” or the timeout expires. The first is flaky on a page that sets the title client-side; the second is not.


Complete Example Session

// ============================================
// PART 1: toBeVisible
// ============================================
import { test, expect } from "@playwright/test";

test("shows the dashboard", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("user@example.com");
  await page.getByLabel("Password").fill("password123");
  await page.getByRole("button", { name: "Sign in" }).click();

  // Retries until the heading is visible
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

// ============================================
// PART 2: toHaveTitle
// ============================================
test("sets the page title", async ({ page }) => {
  await page.goto("/");
  await expect(page).toHaveTitle(/My App/);
});

// ============================================
// PART 3: toContainText vs toHaveText
// ============================================
test("shows the payment status", async ({ page }) => {
  await page.goto("/checkout");
  await page.getByRole("button", { name: "Pay" }).click();

  await expect(page.getByRole("status")).toContainText("Payment");
  await expect(page.getByRole("status")).toHaveText("Payment successful");
});

// ============================================
// PART 4: THE SOFT ASSERTION
// ============================================
test("checks header and footer", async ({ page }) => {
  await page.goto("/");
  await expect.soft(page.getByRole("banner")).toBeVisible();
  await expect.soft(page.getByRole("contentinfo")).toBeVisible();
});

// ============================================
// PART 5: THE VALUE ASSERTION (NO RETRY)
// ============================================
test("reads the title once", async ({ page }) => {
  await page.goto("/");
  // No retry: fails immediately if the title is not yet set
  expect(await page.title()).toBe("My App");
});

The parts covered toBeVisible, toHaveTitle, the text matchers, the soft assertion, and the value assertion that does not retry.


Quick Reference

Visibility Matchers

MatcherPasses When
toBeVisible()Attached, non-empty box, not visibility:hidden
toBeHidden()Detached, no box, or visibility:hidden
not.toBeVisible()Same as toBeHidden

Page and Text Matchers

MatcherAsserts
toHaveTitle(string | regex)Page title
toHaveText(string | regex | array)Exact text
toContainText(string | regex | array)Partial text
toHaveURL(string | regex)Page URL

Retry Configuration

SettingDefaultScope
expect.timeout5sAll web-first assertions
{ timeout } argumentโ€”Per assertion
expect.configure()โ€”Pre-configured expect
expect.soft()โ€”Records failure, continues

Best Practices

โœ… Do This:

// Web-first for async DOM content
await expect(page.getByText("Saved")).toBeVisible();          // โœ…

// Use toContainText for partial matches
await expect(status).toContainText("success");                 // โœ…

// Set a longer timeout per assertion when needed
await expect(page.getByText("Report")).toBeVisible({ timeout: 30_000 }); // โœ…

โŒ Don’t Do This:

// Value assertion on async content
expect(await page.textContent("h1")).toBe("Dashboard");       // โŒ

// Assume opacity: 0 is hidden
await expect(element).toBeHidden(); // fails, it has a box     // โŒ

// Hard-coded wait before the assertion
await page.waitForTimeout(2000);                               // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Flaky assertion on async dataValue assertionWeb-first matcher
toBeHidden fails on opacity: 0Box existsThe element is visible by layout
Assertion times out on slow endpoint5s defaultPer-assertion timeout
Test stops at the first failureHard assertionexpect.soft()

Real-World Examples

1. Visible assertion

await expect(page.getByText("Saved")).toBeVisible();

2. Hidden assertion

await expect(page.getByText("Loading")).toBeHidden();

3. Title assertion

await expect(page).toHaveTitle("Dashboard | My App");

4. Title regex

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

5. Partial text

await expect(status).toContainText("Payment");

6. Exact text

await expect(status).toHaveText("Payment successful");

7. Array text

await expect(items).toHaveText(["One", "Two", "Three"]);

8. Custom timeout

await expect(el).toBeVisible({ timeout: 30_000 });

9. Soft assertion

await expect.soft(el).toBeVisible();

10. Configured expect

const slowExpect = expect.configure({ timeout: 30_000 });

Visual

Visibility Model

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Detached             โ†’ neither visible nor hidden      โ”‚
โ”‚  display:none         โ†’ hidden                          โ”‚
โ”‚  visibility:hidden    โ†’ hidden                          โ”‚
โ”‚  opacity:0            โ†’ VISIBLE (has a box)             โ”‚
โ”‚  Normal               โ†’ visible                         โ”‚
โ”‚                                                         โ”‚
โ”‚  toBeVisible passes only for the last two               โ”‚
โ”‚  toBeHidden passes for detached, none, hidden           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Retry Model

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  expect(locator).toHaveText("X")                        โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Evaluate condition                                     โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚  pass      fail                                         โ”‚
โ”‚    โ”‚         โ”‚                                          โ”‚
โ”‚    โ–ผ         โ–ผ                                          โ”‚
โ”‚  done      wait, re-evaluate                            โ”‚
โ”‚            until timeout                                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Web-First vs Value

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WEB-FIRST                                              โ”‚
โ”‚  expect(page).toHaveTitle("Dashboard")                  โ”‚
โ”‚    โ†’ retries until title matches or 5s                  โ”‚
โ”‚                                                         โ”‚
โ”‚  VALUE                                                  โ”‚
โ”‚  expect(await page.title()).toBe("Dashboard")           โ”‚
โ”‚    โ†’ reads once, fails immediately                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Soft Assertions

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  await expect.soft(a).toBeVisible();  โ†’ fails, continue โ”‚
โ”‚  await expect.soft(b).toBeVisible();  โ†’ passes          โ”‚
โ”‚  await expect.soft(c).toBeVisible();  โ†’ fails, continue โ”‚
โ”‚                                                         โ”‚
โ”‚  At the end: both failures reported                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
VisibilitytoBeVisible() / toBeHidden()
TitletoHaveTitle(string | regex)
Exact texttoHaveText()
Partial texttoContainText()
Default timeout5s
Per-assertion timeout{ timeout } argument
Soft assertionexpect.soft()
Value assertionNo retry

Key takeaways:

  • Web-first matchers retry; value matchers do not. expect(page).toHaveTitle() retries until the title matches. expect(await page.title()).toBe() reads once and fails immediately. The first is the correct assertion for async content.
  • Visibility is about the box, not the paint. An opacity: 0 element is visible by Playwright’s definition because it has a bounding box. toBeHidden() passes for detached, display: none, and visibility: hidden elements.
  • toContainText is the partial match and toHaveText is the exact match. Both retry, and both normalize whitespace. The array form of toHaveText compares multiple elements positionally.
  • The timeout is per assertion and configurable. The default is 5 seconds, and a slow endpoint needs the { timeout } argument or the expect.configure call.
  • expect.soft() records the failure and continues. It is the pattern for asserting on several elements in one test without stopping at the first failure.

Remember: A Playwright assertion on DOM content should be a web-first assertion, because the content may not be ready when the test reads it. The retry is the mechanism that replaces the hard-coded wait. Use toBeVisible and toBeHidden for presence, toHaveTitle and toHaveURL for the page, and toHaveText and toContainText for content. The value assertion is for data that does not change, not for the DOM that is still loading.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!