Popular Assertions in Playwright with TypeScript
Top 5 Assertions That People Use
A guide to the most commonly used assertions in Playwright for robust test automation with TypeScript.
Playwright's expect
function offers a variety of
assertions to validate webpage elements, states, and behaviors. Below
are the most popular ones, with TypeScript examples.
1. toBeVisible
Verifies that an element is visible on the webpage. This is useful for checking if UI components render correctly.
import { test, expect } from '@playwright/test';
test('should display header', async ({ page }) => {
await page.goto('https://example.com');
const header = page.locator('h1');
await expect(header).toBeVisible();
});
This test navigates to a webpage and checks if an
h1
element is visible.
2. toHaveText
Asserts that an element contains the specified text. It can match exact text or a regular expression.
test('should have correct button text', async ({ page }) => {
await page.goto('https://example.com');
const button = page.locator('button#submit');
await expect(button).toHaveText('Submit');
});
Use this to verify text content in buttons, labels, or other elements.
3. toHaveAttribute
Checks if an element has a specific attribute with an expected value,
such as class
, id
, or custom attributes.
test('should have disabled attribute', async ({ page }) => {
await page.goto('https://example.com');
const input = page.locator('input#username');
await expect(input).toHaveAttribute('disabled', '');
});
This is ideal for testing element states like disabled or checked inputs.
4. toBeEnabled / toBeDisabled
Verifies whether an element is enabled or disabled, commonly used for form controls.
test('should have enabled submit button', async ({ page }) => {
await page.goto('https://example.com');
const button = page.locator('button#submit');
await expect(button).toBeEnabled();
});
Use toBeDisabled
for the opposite case.
5. toHaveValue
Asserts that an input element (e.g., input
,
textarea
) has a specific value.
test('should have input value', async ({ page }) => {
await page.goto('https://example.com');
const input = page.locator('input#username');
await input.fill('testuser');
await expect(input).toHaveValue('testuser');
});