Asserting Text, Visibility and State

Most of your Playwright tests will assert on text content, visibility, and element state such as enabled or checked. Using the appropriate assertion for each case makes tests clearer and avoids false positives.

Asserting Text, Visibility and Element State

Playwright provides dedicated assertions like toHaveText, toContainText, toBeVisible, toBeEnabled and toBeChecked. These are designed to work well with locators and auto-waiting.

// text-visibility-state.spec.ts
import { test, expect } from '@playwright/test';

test('updates status message after saving', async ({ page }) => {
  await page.goto('https://demo.myshop.com/profile');

  await page.getByRole('textbox', { name: 'Display name' }).fill('New Name');
  await page.getByRole('button', { name: 'Save changes' }).click();

  const status = page.getByRole('status');
  await expect(status).toBeVisible();
  await expect(status).toHaveText('Profile updated');
});
Note: toHaveText asserts on exact text (optionally trimmed), while toContainText checks for a substring; choose based on how strict you need to be.
Tip: Use state assertions like toBeDisabled or toBeChecked to encode important UI rules, such as buttons being disabled until required fields are filled.
Warning: Overusing toContainText with very generic substrings can accidentally match the wrong element and hide regressions.

You can also assert on element counts and collections, such as expecting a list to have a certain number of items after a filter is applied.

Common Mistakes

Mistake 1 โ€” Using the wrong text assertion for the situation

This can cause fragile or weak checks.

โŒ Wrong: Using toHaveText when texts contain dynamic timestamps or IDs.

โœ… Correct: Use toContainText or regex patterns when parts of the text change.

Mistake 2 โ€” Asserting visibility indirectly through CSS classes only

This ignores actual rendering.

โŒ Wrong: Checking for a hidden class instead of whether the element is visible to the user.

โœ… Correct: Use toBeVisible and toBeHidden to match user-visible behaviour.

🧠 Test Yourself

Which assertion is best for verifying a success message with exact text?