GyaaniGuy

- self made 💻 😎

Automation with playwright - Part 5 Assertions in tests

What are assertions

Assertions are checks to confirm your application behaves as expected during tests.

Assertions validate conditions like page URL, element visibility, text content, form input values, attributes, and more.

Types of Assertions

  • Hard Assertions: Fail immediately and stop test execution.
  • Soft Assertions: Log the failure but allow the test to continue.

Various Assert functions

//  Assert Page URL
await expect(page).toHaveURL('https://example.com');

// Assert Page Title
await expect(page).toHaveTitle('Expected Title');

// Element is Visible
const logo = page.locator('.header-logo');
await expect(logo).toBeVisible();

// Element Enabled/Disabled
const input = page.locator('#search-store');
await expect(input).toBeEnabled();    // or .toBeDisabled()

// Checkbox/Radio is Checked
const radio = page.locator('#gender-male');
await radio.click();
await expect(radio).toBeChecked();
const checkbox = page.locator('#newsletter');
await expect(checkbox).toBeChecked();

// Exact Text Match
await expect(page.locator('.page-title h1')).toHaveText('Register');

// Partial Text Match
await expect(page.locator('.page-title h1')).toContainText('Reg');

// Input Has Value
const email = page.locator('#email');
await email.fill('test@example.com');
await expect(email).toHaveValue('test@example.com');

// Count of Elements
const options = page.locator('select[name=DateOfBirthMonth] option');
await expect(options).toHaveCount(13);

❗ Negative Assertions

await expect(page).not.toHaveURL('https://wrong.com');
await expect(page.locator('#search')).not.toBeVisible();
await expect(page.locator('#subscribe')).not.toBeChecked();
await expect(page.locator('img')).not.toHaveCount(0);

Soft Assertions

await expect.soft(page).toHaveTitle('Store');

If this fails, it logs the failure but continues running the rest of the test.


dated April 2025