Locator Assertions
Locator assertions verify element state. They re-query the DOM on each retry, staying resilient to re-renders in React and similar frameworks.
Element State Matchers
Visibility matchers distinguish visible, hidden, attached, and detached states — important for modals and conditional rendering.
Text matchers support substring, regex, and arrays for lists split across child nodes.
const submit = page.getByRole('button', { name: 'Submit' });
await expect(submit).toBeEnabled();
await expect(submit).toHaveAttribute('type', 'submit');
await expect(page.getByRole('listitem')).toHaveCount(5);
Count assertions help verify lists loaded from API.
Locator Matcher List
toBeVisible / toBeHidden / toBeAttached / toBeDetached
toHaveText / toContainText
toHaveValue / toBeEmpty
toBeChecked / toBeEnabled / toBeDisabled
toHaveClass / toHaveAttribute / toHaveCSS
toHaveCount
toContainText is usually safer than exact toHaveText for dynamic UI. toHaveCSS checks computed styles for visual state. toHaveAccessibleName validates a11y without clicking. - Combine with
filter locators for row-specific checks.
Locator Assertion Cheat Sheet
Pick the matcher for what you need to verify.
| Verify | Matcher |
| Shown on screen | toBeVisible() |
| Removed from DOM | toBeDetached() |
| Input content | toHaveValue('x') |
| Link target | toHaveAttribute('href', '/x') |
| Error styling | toHaveClass(/error/) |
| List length | toHaveCount(n) |
| Disabled button | toBeDisabled() |
| Checked box | toBeChecked() |
Asserting Text in Complex DOM
await expect(page.getByRole('cell', { name: 'Paid' })).toBeVisible();
await expect(page.getByRole('row')).toContainText(['Product', '$9.99']);
Asserting List Lengths
await expect(page.getByRole('row')).toHaveCount(5) retries until exactly five rows exist — ideal after filtering or pagination loads.
Common Mistakes
- toHaveText when whitespace/normalization differs — use contain or regex.
- Asserting visible when element exists but opacity 0.
- toHaveCount before network finishes — pair with proper wait.
- Checking classes tied to CSS modules that change hash each build.
Key Takeaways
- Locator assertions auto-retry through re-renders.
- Choose visibility matcher matching actual UX requirement.
- Count and text assertions validate data-loaded UI.
- Prefer contain text and regex over brittle exact strings.
Pro Tip
On failure, Playwright prints locator resolution log — use it to see which elements matched before adjusting the locator.