Run Web Automation Tests at Scale with Agentic AI

Generate tests with AI agents or automate test suites with Selenium, Playwright and other frameworks. Run tests in parallel on TestMu AI scalable cloud grid.

Testing

A Complete Guide To Playwright Assertions

Part of: Playwright

Discover the basics of Playwright assertions with this comprehensive tutorial. Learn how to use this tool for efficient and effective testing.

Last Updated on:

With increasing changes in testing patterns, automation testing frameworks available in the market have risen significantly. Selenium has been in the market for almost a decade, but tools such as Playwright and Cypress are evolving daily.

Every tool has pros and cons; however, Playwright execution speed is faster because it uses WebSocket instead of WebDriver API and HTTP. During test execution, WebSocket stays open, so everything is sent over a single connection.

Playwright assertions take care of test flakiness and have an inbuilt retry mechanism. It uses the expect library from Jest for test assertions. The expect library gives you access to several "matchers" that validate different conditions like toBeChecked, toBeVisible, toContainText, toBeVisible, toHaveText, etc. Playwright assertions default timeout is set to 5 seconds.

In this Playwright tutorial, we will look into these Playwright assertion types in much more detail.

Let's quickly look into what test assertions are in the Playwright automation framework.

Key Takeaways

  • A test assertion compares the actual outcome of a step with the expected outcome, so a Playwright test fails at the exact point where the application state stops matching expectations.
  • Playwright assertions use the expect library from Jest and default to a 5 second timeout, retrying the check until the condition is met instead of failing on the first attempt.
  • Soft assertions written with expect.soft() mark a Playwright test as failed but let the remaining steps run, and soft assertions work only with the Playwright test runner.
  • Playwright groups web-first assertions into the LocatorAssertions class, covering matchers such as toBeChecked, toBeVisible, toContainText, toHaveAttribute, toHaveClass, toHaveCount and toHaveValue.
  • PageAssertions in Playwright validate page level state, where toHaveTitle checks the page title and toHaveURL checks the current URL, and both matchers accept a regular expression for partial matches.
  • Adding not before any Playwright matcher asserts the opposite condition, so expect(page).not.toHaveURL() confirms that the browser is not on the given URL.
  • expect.poll retries a value or API check on default intervals of 100, 250, 500 and 1000 milliseconds, and both the interval list and the timeout can be set per assertion.
  • Running a Playwright suite on the TestMu AI cloud grid gives on-demand access to 3000+ real desktop and mobile environments and parallel execution that cuts total run time.

What are Test Assertions?

An assertion is a part of the test automation process where you compare/match the actual outcome with the expected outcome. This means checking to verify that the application's state is what we expect.

Let's say John wants to purchase a product by navigating to a website by clicking on the Category menu and then clicking on the Category, selecting the product, adding to the cart, checkout, and making the payment. We will look into this example step-by-step using TestMu AI eCommerce Playground.

Step-by-step test approach


Step No#ActionVerification
1Navigate to eCommerce Playground Website.1.Verify the user is navigated to the eCommerce website.
2.Verify page title is Your Store.
2Click on Shop by Category.1.Verify Shop by Category menu is visible.
2.Verify Top categories is shown to the user.
3Click on the Components category.1.Verify the user is redirected to the Components page
2.Verify the page title is ‘Components’
3.Verify ‘HTC Touch HD’ is shown in the list.
4Click on the first product, ‘HTC Touch HD’1.Verify the user is navigated to the ‘HTC Touch HD’ product details page.
2.Verify page title is ‘HTC Touch HD’ Verify Availability is shown as ‘In Stock’
3.Verify the ‘ADD To CART’ button is enabled.
5Click on the ‘ADD To CART’ button.1.Verify product is successfully added to the cart.
6Click on the ‘Cart’ icon.1.Verify the Cart side panel is open
2.Verify the Checkout button is shown to the user
7Click on the ‘Checkout’ button.1.Verify the user is redirected to the Checkout page.
2.Verify product details are shown in the right side pane.
Since you didn’t log into the application on the right-hand side, you will also see the Registration/Login/Guest flow.

In the above example, you can see how you can add assertions for each state of the page and transition. You can always add an assertion in such a way it is raised whenever there are issues/errors in the user journey. In the following sections, you will learn more about Playwright and different types of Playwright assertions.

The assertion examples below run in a Playwright project. To create one, follow how to install Playwright.

Youtube thumbnail

Deep Diving into Playwright Assertions

While testing a condition, you want different ways to assert, and Playwright makes this possible much simpler by using expect. It's a feature that allows you to assert the state of a web page or an element within a web page.

This can include checking the text content of an element, the value of an input field, or the presence of a specific CSS class. You can learn more about it through this blog on locator strategies.

Since you already know what expect is, let's now look at different Playwright assertions.


AssertionsDescription
expect(locator).toBeAttached()Expect to verify Element is attached to the DOM
expect(locator).toBeChecked()Expect to verify Checkbox is checked
expect(locator).toBeDisabled()Expect to verify Element is disabled
expect(locator).toBeEditable()Expect to verify Element is editable
expect(locator).toBeEmpty()Expect to verify the Container is empty
expect(locator).toBeEnabled()Expect to verify Element is enabled
expect(locator).toBeFocused()Expect to verify Element is focused
expect(locator).toBeHidden()Expect to verify Element is not visible or hidden
expect(locator).toBeInViewport()Expect to verify Element intersects the viewport
expect(locator).toBeVisible()Expect to verify Element is visible
expect(locator).toContainText()Expect to verify Element contains text
expect(locator).toContainClass()Expect to verify Element has the specified CSS classes
expect(locator).toHaveAccessibleDescription()Expect to verify Element has a matching accessible description
expect(locator).toHaveAccessibleName()Expect to verify Element has a matching accessible name
expect(locator).toHaveAttribute()Expect to verify Element has a DOM attribute
expect(locator).toHaveClass()Expect to verify Element has a class property
expect(locator).toHaveCount()Expect to verify a List has the exact number of children
expect(locator).toHaveCSS()Expect to verify Element has CSS property
expect(locator).toHaveId()Expect to verify Element has an ID
expect(locator).toHaveJSProperty()Expect to verify Element has a JavaScript property
expect(locator).toHaveRole()Expect to verify Element has a specific ARIA role
expect(locator).toHaveScreenshot()Expect to verify Element has a screenshot
expect(locator).toHaveText()Expect to verify Element matches text
expect(locator).toHaveValue()Expect to verify Input has a value
expect(locator).toHaveValues()Expect to verify Select has options selected
expect(locator).toMatchAriaSnapshot()Expect to verify Element matches the ARIA snapshot
expect(page).toMatchAriaSnapshot()Expect to verify Page matches the ARIA snapshot
expect(page).toHaveScreenshot()Expect to verify Page has a screenshot
expect(page).toHaveTitle()Expect to verify Page has a title
expect(page).toHaveURL()Expect to verify Page has a URL
expect(apiResponse).toBeOK()Expect to verify Response has an OK status

We will execute the tests on the TestMu AI cloud, where Playwright connects to a remote browser over a WebSocket endpoint in the way Selenium tests connect to a Selenium Grid. You need to import TestMu AI-setup, which you can find on my GitHub Repo, along with all the examples in this guide. To run an example only on your local machine, import test from @playwright/test in place of the setup file.

Negative Matchers

Negative matchers are used when you want to verify certain conditions are not matched. It's a kind of verification opposite to the true condition:

Example:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Negative matchers test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect(page.getByText('Top Category'), 'top category text should not be visible').not.toBeVisible();
});

Walkthrough:

Line 6: not.toBeVisible() is the negative matcher. It passes when the element is not visible on the page.

I will explain the complete code in the Playwright Locator Assertions section.

Execution:

Workspace Execution

Soft Assertions

When several verification steps need to be added on a page, or some are less important, you don't want test execution to stop when a certain condition is not matched, or an assertion fails.

In soft Playwright assertion, you are just verifying some condition, and it doesn’t interrupt the whole execution if the condition is not satisfied but marks the test as failed. Soft assertions only work with the Playwright test runner.

Example:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Soft assertion test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect.soft(page.getByText('Top Category'), 'top category should be visible').toBeVisible();
  await expect(page).toHaveTitle("Your Store");
});

Line 6: It's a soft assertion. The home page has no Top Category text, so it fails on purpose, the test is marked as failed, and execution still moves on to line 7.

Line 7: It's a hard assertion. If the condition doesn’t match, the test will be marked as failed, and execution will be stopped. The hard Playwright assertion will be simply written as expect, unlike the soft Playwright assertion.

You can read this blog on Soft and Hard Asserts to learn more about them.

Execution:

Google chrome playwright pageError page hooks

In the HTML report, you will see only X for the soft Playwright assertion, and it continued with the remaining tests and verified the expected condition, which passed.

Custom Expect Message

With the failure when you want to show a custom error message while doing expect or verification, we use a custom expect message.

Implementation:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Custom expect message test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect(page.getByText('Top Category'), 'top category should be visible').toBeVisible();
});

The home page has no Top Category text, so this assertion fails, and the error in the report starts with top category should be visible.

Expect Polling

expect.poll turns a synchronous expect into a polling one. It calls the function you pass again and again until the returned value satisfies the matcher or the timeout runs out.

Implementation:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Fetch platform along with browsers and version supported using Playwright Expect Poll test', async ({ page }) => {
  await expect.poll(async () => {
    const response = await page.request.get('https://api.lambdatest.com/automation/api/v1/platforms');
    return response.status();
  }, {
    message: 'Response was either not 200 or timeout',
    timeout: 10000,
  }).toBe(200);
});

Code Walkthrough:

Line 5: expect.poll is like a wait. It calls the function until the status it returns passes toBe(200).

Line 9: It's a custom error message you want to log.

Line 10: It waits for 10 seconds. If not, it will time out. The default poll is 5 seconds. You need to pass 0 in case you don’t want to timeout

Execution:

Expect Polling

Custom Polling Intervals

You can also specify the custom polling intervals. Probe, wait 2 seconds, probe, wait 4 seconds, probe, wait 10 seconds, probe, wait 10 seconds. Default intervals are [100, 250, 500, 1000].

Implementation:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Custom Polling test', async ({ page }) => {
  await expect.poll(async () => {
    const response = await page.request.get('https://api.lambdatest.com/automation/api/v1/platforms');
    return response.status();
  }, {
    message: 'Response was either not 200 or timeout',
    intervals: [2_000, 4_000, 10_000],
    timeout: 60000,
  }).toBe(200);
});

Code Walkthrough:

Line 10: It polls with intervals specified like [2_000, 4_000, 10_000] (mentioned in ms)

Execution:

Custom Polling Intervals

Expect Retrying

If the expected condition doesn't match, toPass retries the block. Its own timeout defaults to 0, which means no limit, so the retries go on until the test timeout (30000ms by default) stops the test.

Implementation:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Expect Retry test', async ({ page }) => {
  await expect(async () => {
    const response = await page.request.get('https://api.lambdatest.com/automation/api/v1/platforms');
    expect(response.status()).toBe(200);
  }).toPass();
});

Code Walkthrough:

Line 7: It is going to check the expected condition to match, here we have a status code as 200. If suppose we are not receiving the status code as 200, then it will keep retrying until the test timeout.

Execution:

Expect Retrying

For demonstration, I am changing the status code 200 to 201 to mimic a failure. With this, it will keep trying until the 30000ms test timeout, after which the test fails.

mimic a failurefail the test Playwright Assertions

Custom Timeout For Retry Intervals

If the expected condition doesn’t match, it will retry for the specified intervals.

Implementation:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Expect Custom Retry test', async ({ page }) => {
  await expect(async () => {
    const response = await page.request.get('https://api.lambdatest.com/automation/api/v1/platforms');
    expect(response.status()).toBe(200);
  }).toPass({
    intervals: [1_000, 2_000, 10_000],
    timeout: 60_000
  });
});

Code Walkthrough:

Line 9: You can specify the custom retry intervals. Probe, wait 1s, probe, wait 2s, probe, wait 10s, probe, wait 10s. Default intervals are [100, 250, 500, 1000].

Execution:

Custom Timeout For Retry Intervals

Playwright Locator Assertions

Locator assertions in the tests are provided in LocatorAssertions class. A new instance of LocatorAssertions is created by invoking expect().

Implementation:

Playwright Locator Assertions

For simplification, every Playwright assertion method is explained as an individual test.

toBeChecked

It's a way to ensure that the specified locator of the Checkbox type is checked or unchecked.

Sample Usage:

// Example 1
await expect(page.getByLabel('Subscribe to newsletter')).toBeChecked();

// Example 2
const privacyCheckbox = page.getByRole('checkbox', { name: 'I have read and agree to the Privacy Policy' });
await expect(privacyCheckbox).toBeChecked();

Parameters:

Parameters Playwright Locator Assertions

Implementation:

Shown below is an example that demonstrates the usage of toBeChecked expect in Playwright:

Implementation Playwright Locator Assertions
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Registration Privacy Policy checkbox is checked test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const privacyCheckbox = page.getByRole('checkbox', { name: 'I have read and agree to the Privacy Policy' });
  await page.locator("label[for='input-agree']").click();
  await expect(privacyCheckbox).toBeChecked();
});

Code Walkthrough:

Line 1: Importing test, which is called from the lambdatest-setup.js file, so that execution can also be done on TestMu AI.

Line 2: Import expect, which is called from @playwright/test.

Line 4: The Test is a block where you will write your test. You can have multiple tests in a spec

Line 5: Navigating to the test URL.

Line 6: The const is created to store locators.

Line 7: Clicking on the Privacy checkbox, as by default, it's unchecked on the page. The click targets the label because this page covers the real checkbox input with a styled label, and a click on the input itself does not get through.

Line 8: The expecting locator to be checked on the page.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to be checked.

Execution Playwright Locator Assertions

toBeDisabled

It's used when you want to ensure the locator is disabled, and it will not accept any input or action. An element is disabled if it has the disabled attribute or is disabled through aria-disabled. Only native controls such as button, input, select, textarea, option and optgroup can be disabled with the disabled attribute. On other elements the browser ignores it.

Sample Usage:

// Example 1
await expect(page.locator('button.submit')).toBeDisabled();

// Example 2
const firstNameLoc = page.getByLabel('First Name');
await expect(firstNameLoc).not.toBeDisabled();

Parameters:

Parameters toBeDisabled

Implementation:

Shown below is an example that demonstrates the usage of toBeDisabled expect in Playwright:

usage of toBeDisable
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('First name field on Registration page to not be disabled test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstNameLoc = page.getByLabel('First Name');
  await expect(firstNameLoc).not.toBeDisabled();
})

Code Walkthrough:

Line 7: Expect will verify if the element is disabled. In the above example, you will see we are using not because that field is not disabled, so we are verifying negative conditions.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to not be disabled.

Execution toBeDisable

toBeEditable

It's used to ensure that the specified locator is editable and will accept any input value.

Sample Usage:

const firstNameLoc = page.getByLabel('First Name');
await expect(firstNameLoc).toBeEditable();

Parameters:

Parameters toBeEditable

Implementation:

Shown below is an example that demonstrates the usage of toBeEditable expect in Playwright:

Implementation toBeEditable
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('First name field on Registration page to be editable test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstNameLoc = page.getByLabel('First Name');
  await expect(firstNameLoc).toBeEditable();
});

Code Walkthrough:

Line 7: Expect will verify given locator is editable.

Execution:

Here is the execution output, which indicates that no expected condition failed and the specified locator is matched to be Editable.

$ npx playwright test tests/to-be-editable.spec.js

Running 1 test using 1 worker

  ✓  1 [Google Chrome] › tests/to-be-editable.spec.js:4:1 › First name field on Registration page to be editable test (6.0s)

  1 passed (6.8s)

toBeEnabled

It's used to ensure the element is enabled further if you want to perform any action.

Sample Usage:

// Example 1
await expect(page.locator('button.submit')).toBeEnabled();

// Example 2
const continueBtn = page.getByRole('button', { name: 'Continue' });
await expect(continueBtn).toBeEnabled();

Parameters:

Parameters toBeEnabled

Implementation:

Shown below is an example that demonstrates the usage of toBeEnabled expect in Playwright:

Implementation toBeEnabled
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Continue button on Registration page to be enabled test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const continueBtn = page.getByRole('button', { name: 'Continue' });
  await expect(continueBtn).toBeEnabled();
});

Code Walkthrough:

Line 7: Expect will verify given locator is enabled.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to be Enabled.

Execution toBeEnabled

toBeFocused

It's used to ensure the locator is focused on the DOM node.

Sample Usage:

// Example 1
await expect(page.getByRole('textbox')).toBeFocused();

// Example 2
const firstName = page.getByLabel('First Name');
await firstName.focus(); // Use this when the element does not have focus yet.
await expect(firstName).toBeFocused();

Parameters:

Parameters toBeFocused
Run tests up to 70% faster on the TestMu AI cloud grid

Implementation:

Shown below is an example that demonstrates the usage of toBeFocused expect in Playwright:

Implementation toBeFocused
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('First name field on Registration page to be focused test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstName = page.getByLabel('First Name');
  await firstName.focus();
  await expect(firstName).toBeFocused();
});

Code Walkthrough:

Line 7: When the focus is not on the HTML DOM node, then use .focus(). If the focus is already there, then you can skip this step.

Line 8: Expect will verify given locator is focused.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to be Focused.

tobefocused execution

toBeVisible

It ensures that the specified locator is a visible DOM node

Sample Usage:

const loginLi = page.locator('#column-right').getByRole('link', { name: 'Login' });
await expect(loginLi).toBeVisible();

Parameters:

tobevisible parameters

Implementation:

Shown below is an example that demonstrates the usage of toBeVisible expect in Playwright:

tobevisible implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Login link is visible on right handside of Registration page', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const loginLi = page.locator('#column-right').getByRole('link', { name: 'Login' });
  await expect(loginLi).toBeVisible();
});

Code Walkthrough:

Line 7: Expect will verify given locator is visible DOM node.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to be Visible.

tobevisible execution

toContainText

It ensures that the specified locator points to an element that contains given text. You can use regular expressions to verify string and substring.

Sample Usage:

const warningMsg = page.locator('.alert-danger');
await expect(warningMsg).toContainText("Warning: You must agree to the Privacy Policy!");
await expect(warningMsg).toContainText("agree to the Privacy");

Parameters:

tocontaintext-parameters

Implementation:

Shown below is an example that demonstrates the usage of toContainText expect in Playwright:

tocontaintext-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Registration page validation message to contain text test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const continueBtn = page.getByRole('button', { name: 'Continue' });
  await continueBtn.click();
  const warningMsg = page.locator('.alert-danger');
  await expect(warningMsg).toContainText("Warning: You must agree to the Privacy Policy!");
  await expect(warningMsg).toContainText("agree to the Privacy");
});

Code Walkthrough:

Line 6: Locator of Continue button is stored in a constant.

Line 7: Click on the Continue button.

Line 8: Locator of Warning message is stored in a constant.

Line 9: Expect will verify given string is present in the locator.

Line 10: Expect will verify given substring is present in the locator.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to contain text.

tocontaintext-execution

toHaveAttribute

It ensures the Locator points to an element with a given attribute.

Sample Usage:

const noNewsLetterSubscribe = page.locator("#input-newsletter-no");
await expect(noNewsLetterSubscribe).toHaveAttribute("type", "radio");

Parameters:

tohaveattribute-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveAttribute expect in Playwright.

tohaveattribute-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Registration page h1 element to have attribute test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const noNewsLetterSubscribe = page.locator("#input-newsletter-no");
  await expect(noNewsLetterSubscribe).toHaveAttribute("type", "radio");
});

Code Walkthrough:

Line 6: Locator of No radio button is stored in a constant.

Line 7: Expect will verify given locator is having type attribute with value as radio.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have an attribute.

Playwright passing test output

toHaveClass

This ensures that the locator points to an element with specific CSS classes. It must also be an exact match or use a relaxed regular expression.

Sample Usage:

const h1 = page.getByRole('heading', { level: 1 });
await expect(h1).toHaveClass("page-title h3");

Parameters:

tohaveclass-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveClass expect in Playwright:

tohaveclass-implementation

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Registration page h1 element to have class test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const h1 = page.getByRole('heading', { level: 1 });
  await expect(h1).toHaveClass("page-title h3");
});

Code Walkthrough:

Line 6: Locator of h1 element is stored in a constant.

Line 7: Expect will verify given locator is class type attribute with value as page-title h3.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have class.

tohaveclass-execution

toHaveCount

This ensures that Locator finds the exact number of DOM nodes.

Sample Usage:

// Example 1
await expect(page.locator('list > .component')).toHaveCount(3);

// Example 2
const formControl = page.locator('input.form-control');
await expect(formControl).toHaveCount(6);

Parameters:

tohavecount-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveCount expect in Playwright:

tohavecount-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Form Control occurrences on Registration page test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const formControl = page.locator('input.form-control');
  await expect(formControl).toHaveCount(6);
});

Code Walkthrough:

Line 6: Locator of form-control element is stored in a constant.

Line 7: Expect will verify given locator occurrences in the DOM node. Here in this example, we have 6 such elements.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have count.

tohavecount-execution

toHaveCSS

This ensures that the Locator resolves the element with a specific calculated CSS style.

Sample Usage:

const firstname = page.locator("#input-firstname");
await expect(firstname).toHaveCSS("display", "block");

Parameters:

tohavecss-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveCSS expect in Playwright:

tohavecss-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('First name on Registration page to have CSS test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstname = page.locator("#input-firstname");
  await expect(firstname).toHaveCSS("display", "block");
});

Code Walkthrough:

Line 6: The locator of the first name input is stored in a constant.

Line 7: Expect will verify the computed CSS display property of the located element is block.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have CSS.

tohavecss-execution

toHaveId

This ensures that the locator points to an element with the given DOM node ID.

Sample Usage:

const firstname = page.getByLabel('First Name');
await expect(firstname).toHaveId("input-firstname");

Parameters:

tohaveid-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveId expect in Playwright:

tohaveid-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('First name on Registration page to have Id test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstname = page.getByLabel('First Name');
  await expect(firstname).toHaveId("input-firstname");
});

Code Walkthrough:

Line 6: The locator of the firstname element is stored in a constant.

Line 7: Expect will verify given locator has an Id of input-firstname.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have Id.

tohaveid-execution

toHaveText

This ensures that the Locator points to the element with the given text. You can also use regular expressions for the value.

Sample Usage:

const firstname = page.locator("label[for='input-firstname']");
await expect(firstname).toHaveText("First Name");

Parameters:

tohavetext-parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveText expect in Playwright:

tohavetext-implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Registration page is having text First name', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const firstname = page.locator("label[for='input-firstname']");
  await expect(firstname).toHaveText("First Name");
});

Code Walkthrough:

Line 6: The locator of the firstname element is stored in a constant.

Line 7: Expect will verify given locator has text First Name.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have text.

Playwright Locator Assertions toHaveText

toHaveValue

This ensures that the Locator points to the element with the given input value. You can also use regular expressions for the value.

Sample Usage:

const newsletterYesRadio = page.locator("#input-newsletter-yes");
await expect(newsletterYesRadio).toHaveValue("1");

Parameters:

To have value parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveValue expect in Playwright:

toHaveValue Implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Newsletter Yes radio is having value 1', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');
  const newsletterYesRadio = page.locator("#input-newsletter-yes");
  await expect(newsletterYesRadio).toHaveValue("1");
});

Code Walkthrough:

Line 6: The locator of the Yes radio button is stored in a constant.

Line 7: Expect will verify given locator has value 1.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have value.

toHaveValue Execution

toHaveValues

This ensures that the locator points to a multi-select box/combo box (i.e., a select with the multiple attribute), and the specified values are selected.

Sample Usage:

const countrySelectorLoc = page.locator("#multi-select");
await countrySelectorLoc.selectOption(["California", "Florida", "New Jersey"]);
await expect(countrySelectorLoc).toHaveValues([/California/, /Florida/, /New Jersey/]);

Parameters:

toHaveValues Parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveValues expect in Playwright:

toHaveValues Implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('Multi Select List of Country', async ({ page }) => {
  await page.goto('https://www.testmuai.com/selenium-playground/select-dropdown-demo');
  const countrySelectorLoc = page.locator("#multi-select");
  await countrySelectorLoc.selectOption(["California", "Florida", "New Jersey"]);
  await expect(countrySelectorLoc).toHaveValues([/California/, /Florida/, /New Jersey/]);
});

Code Walkthrough:

Line 6: The locator of the multi-select list is stored in a constant.

Line 7: Three options are selected in the list.

Line 8: Expect will verify the list has those three values selected.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified locator is matched to have values.

toHaveValues Execution

Playwright PageAssertions

By using PageAssertions, you can make Playwright assertions about the page state in the tests. It creates a new instance of PageAssertions by calling expect().

Playwright PageAssertions

Let’s look into some of the PageAssertions types in the sections below.

toHaveTitle

It ensures that the page has the given title. It helps you in adding a verification when you are navigating through the page.

Sample Usage:

await expect(page).toHaveTitle("Your Store");
await expect(page).toHaveTitle(/Store/);

Parameters:

toHaveTitle Parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveTitle expect in Playwright:

toHaveTitle Implementation
const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('homepage has title', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect(page).toHaveTitle("Your Store");
  await expect(page).toHaveTitle(/Store/);
});

Code Walkthrough:

Line 6: It will verify the complete string mentioned in the title.

Line 7: It will verify the part of the string using RegExp.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified page Title is matched.

toHaveTitle Execution

toHaveURL

It ensures that the page has the given URL. It helps you in adding a verification when you are navigating through the page.

Sample Usage:

await expect(page).toHaveURL("https://ecommerce-playground.lambdatest.io");
await expect(page).toHaveURL(/ecommerce/);

Parameters:

toHaveURL Parameters

Implementation:

Shown below is an example that demonstrates the usage of toHaveURL expect in Playwright:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('LambdaTest Playground URL test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect(page).toHaveURL("https://ecommerce-playground.lambdatest.io");
  await expect(page).toHaveURL(/ecommerce/);
});

Code Walkthrough:

Line 6: It will verify the complete URL string.

Line 7: It will verify the part of the URL string using RegExp.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the specified page URL is matched.

toHaveURL Execution

not (Properties)

It checks to ensure the opposite condition. In the above example, you saw that the URL was matched. Now you will see how not is used to check the opposite condition, which should not match.

Sample Usage:

await expect(page).not.toHaveURL("https://abc.lambdatest.io");
await expect(page).not.toHaveURL(/404/);

Implementation:

Shown below is an example that demonstrates the usage of not.toHaveURL expect in Playwright:

const { test } = require("../lambdatest-setup");
const { expect } = require("@playwright/test");

test('LambdaTest Playground URL Not To Have test', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io');
  await expect(page).not.toHaveURL("https://abc.lambdatest.io");
  await expect(page).not.toHaveURL(/404/);
});

Code Walkthrough:

Line 6: It will verify the complete URL string doesn’t match.

Line 7: It will verify the part of the URL string that doesn’t match using RegExp.

Execution:

Here is the execution snapshot, which indicates that no expected condition failed and the URL doesn’t match.

not (Properties) Execution

Key Takeaway: Playwright assertions cover negative matchers with not, soft assertions with expect.soft(), custom failure messages, polling through expect.poll, and retries of a whole block through toPass. The LocatorAssertions class supplies element level matchers such as toBeChecked, toBeEditable, toContainText, toHaveClass and toHaveCount, while PageAssertions supplies the page level matchers toHaveTitle and toHaveURL.

Running your Playwright tests on the cloud grid

Cloud-based testing platforms like TestMu AI help you perform Playwright automated testing at scale across 50+ browser versions. You can also run your Playwright automation scripts in parallel and cut down execution times by multiple folds.

Here are some other features that make Playwright testing a breeze with TestMu AI.

  • On-demand access to 3000+ real desktop and mobile environments.
  • Get 70% faster test execution with HyperExecute - an end-to-end test orchestration cloud.
  • Leverage Test At Scale to mitigate test flakiness, shorten job times, and get faster feedback on code changes.

Assertion heavy suites carry a maintenance cost, because a renamed element breaks the locator behind toBeVisible or toHaveText. KaneAI, the GenAI testing agent from TestMu AI, authors test steps and smart assertions from natural language instructions, re-anchors those steps through self-healing when the UI changes, and exports the finished test to Playwright so the suite stays in the same framework.

Youtube thumbnail

You can also subscribe to the TestMu AI YouTube Channel and stay updated with the latest tutorial around Playwright browser testing, Cypress E2E testing, Mobile App Testing, and more.

To execute the test on TestMu AI, we will add a script in package.json with a few other minor changes like description and keywords. However, it's optional.

{
  "name": "playwright-lambdatest-javascript",
  "version": "1.0.0",
  "description": "This is Test Automation framework designed using Playwright, and JavaScript to execute on LambdaTest",
  "main": "index.js",
  "scripts": {
    "clean": "rimraf playwright-report && rimraf allure-results && rimraf allure-report",
    "test": "npm run clean && npx playwright test",
    "lambdatest": "npm run clean && npx playwright test --config=./lambdatest.config.js --reporter=line,html,allure-playwright",
    "allure-report": "npx allure generate ./allure-results && allure open"
  },
  "keywords": [
    "node",
    "javascript",
    "allure-report",
    "rimraf",
    "lambdatest",
    "allure-reporting",
    "playwright-tests",
    "lambdatest-playwright"
  ],
  "author": "Code with MMAK",
  "license": "ISC",
  "devDependencies": {
    "@playwright/test": "^1.64.0",
    "allure-commandline": "^2.46.1",
    "allure-playwright": "^3.13.0",
    "playwright": "^1.64.0",
    "rimraf": "^6.1.3"
  }
}
TestMu AI

With all configuration done, now to run the test on TestMu AI Cloud type npm run lambdatest on the terminal.

You will see that test execution starts and the status of each test will be reported in the terminal, and default HTML report.

Terminal Results:

Terminal Results

Default HTML Report:

Go to the Project root directory: ./playwright-report/index.html and open the HTML report.

HTML Report

Result on TestMu AI Dashboard:

LambdaTest Dashboard

Expanded view of test result:

Expanded Result

Conclusion

You now might have a fair understanding of how Playwright assertions or expect work. Also, you saw how you could run the tests on a cloud grid. The tester should only worry about the tests, not the test configuration and maintenance. With the cloud grid solution, you can run the tests on almost all the browser and OS configurations without you being worried about how to maintain them.

Furthermore, it allows you to run tests in parallel, which cuts the time and cost so that you can write more effective tests.

Test across 3000+ browser and OS environments with TestMu AI

Testing from the terminal? Kane CLI by TestMu AI lets SDETs and developers plan, write, run and debug tests from the command line.

To run your first test, start free, or
for a full walkthrough of the product.

Author

...

Prince Dewani

Blogs: 30

  • Linkedin

Prince Dewani is a Community Contributor at TestMu AI specializing in AI agents, software testing, QA, and SEO. He is certified in Selenium, Cypress, Playwright, Appium, Automation Testing, and KaneAI, and presented academic research on AI agents at PBCON-01. At TestMu AI, he has also carried out extensive cross-browser research on the support of modern web technologies such as WebGPU, WebAssembly, WebXR, WebGL2 and other web technologies, validating their compatibility and feature parity across major browsers and rendering engines through rigorous hands-on testing. Prince has hands-on experience building AI agent workflows using Anthropic Claude, Google Antigravity, n8n, LangChain, and other agentic frameworks, and works regularly with MCP and A2A protocols. He shares his work with 5,500+ QA engineers, developers, DevOps experts, tech leaders, and AI agent practitioners on LinkedIn.

Reviewer

...

Parth Mistry

Reviewer

  • Linkedin

Parth Mistry is a Member of Technical Staff at TestMu AI, building SmartUI, the visual regression testing product. He developed and owns the SmartUI CLI, a modular TypeScript tool built on Playwright for multi-browser automation, and built the Storybook CLI for visual regression of UI components. He maintains cross-language SDKs in Python, Java, Ruby, C#, and Node.js, and engineered a Node-based visual rendering service on Kafka, Redis, MySQL, and S3. His migration of that service to an event-driven, KEDA-autoscaled architecture improved execution speed by 60% and cut annual infrastructure cost by $9,600. He also built the end-to-end SmartUI integration with KaneAI. Parth is a Google Summer of Code 2024 contributor and an alumnus of IIT Jodhpur.

Playwright Assertions FAQs

Did you find this page helpful?

More Related Learning Hubs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests