Asserting what an element contains

Exact or partial text

toHaveText() compares the whole text, after collapsing extra whitespace. toContainText() only needs a part of it:

const paragraph = page.getByTestId('text-content');

await expect(paragraph).toHaveText('This is visible text inside a paragraph.');
await expect(paragraph).toContainText('visible text');

Text across several tags

Hello <strong>Playwright</strong> is one piece of text to Playwright, even though it spans two elements:

await expect(page.getByTestId('nested-content')).toHaveText('Hello Playwright');

Values, attributes and state

const input = page.getByLabel('Input value');
await expect(input).toHaveValue('Initial value');
await expect(input).not.toBeEditable(); // read-only

const link = page.getByTestId('attribute-link');
await expect(link).toHaveAttribute('href', '/content/attributes');
await expect(link).toHaveAttribute('target', '_blank');
await expect(link).toHaveId('test-link');
await expect(link).toHaveClass('special-link');

Visible text vs accessible name

The link shows "Open page", but its aria-label makes its accessible name "Open attribute test page". getByRole() matches the accessible name, and getByText() matches the visible text:

await expect(page.getByRole('link', { name: 'Open attribute test page' })).toBeVisible();
await expect(page.getByText('Open page')).toBeVisible();

Text Content

This is visible text inside a paragraph.

Hello Playwright

Input Value

Attributes

Open page

Element State