Playwright Assertions Cheat Sheet

Playwright provides powerful, auto-waiting assertions that make tests more stable and reliable. Using the expect() API, Playwright automatically waits for conditions to be satisfied before failing a test. Assertions retry until they either pass or reach the timeout limit, so manual waits are not required in most cases.

This section covers the most commonly used Playwright assertions with simple examples and best practices for beginners.

Basic Syntax

await expect(target).assertionMethod(expectedValue);


Syntax Explanation

expect(): Playwright’s assertion API
target: Can be a locator, page, or API response
matcher: The assertion method (for example: toBeVisible, toHaveText)
expectedValue: The value you want to validate (text, URL, count, etc.)

Visibility Assertions

await expect(locator).toBeVisible();
await expect(locator).toBeHidden();


Use these to check whether an element is shown or hidden on the page.

Text Assertions

await expect(locator).toHaveText('Submit');
await expect(locator).toContainText('Success');


toHaveText() checks exact text
toContainText() checks partial text

Attribute Assertions

await expect(locator).toHaveAttribute('type', 'email');
await expect(locator).toHaveClass(/active/);


Useful for validating element attributes or CSS classes.

Input Field Assertions

await expect(locator).toHaveValue('john_doe');
await expect(locator).toBeEmpty();


Commonly used for input boxes, text areas, and forms.

Enabled / Disabled Assertions

await expect(locator).toBeEnabled();
await expect(locator).toBeDisabled();


Helpful for validating buttons and form controls.

Checkbox & Radio Button Assertions

await expect(locator).toBeChecked();
await expect(locator).not.toBeChecked();


Works for checkboxes and radio buttons.

Count Assertions (Multiple Elements)

await expect(locator).toHaveCount(3);


Used when validating lists, tables, or repeated elements.

Page-Level Assertions

await expect(page).toHaveTitle('Dashboard');
await expect(page).toHaveURL('https://example.com/dashboard');


Validates browser-level properties like URL and page title.

Assertion with NOT Condition

await expect(locator).not.toBeVisible();
await expect(locator).not.toHaveText('Error');


Used when verifying something should not happen.

API Response Assertions

expect(response.status()).toBe(200);
expect(response.ok()).toBeTruthy();


Soft Assertions (Continue Test on Failure)

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


Test continues even if the assertion fails. Useful for reporting multiple issues in one test

Best Practices for Beginners

     - Prefer Playwright assertions over manual waits
     - Assert what the user sees, not implementation details
     - Keep assertions in test files (page files focus on actions)
     - Use toContainText() instead of toHaveText() when text may change
 

Related Tutorials