Assertions in Playwright

Hello everyone, Lets learn about assertions in this article. Assertions are checks in the test to check whether the application is behaving as expected. Why Assertions? They help you to validate the state of elements, text is present, attributes on the page and test will fail which signals a bug or unexpected behavior

I will simplify and go through the types of assertions in playwright

1. Visibility & Existence

To check whether element is visible or hidden, we can use

expect(locator).to_be_visible()Element is visible
expect(locator).to_be_hidden()Element is not visible

2. Text Content

To check for an exact match use to_have_text() and to checks if the string appears anywhere inside the element text use to_contain_text()

expect(locator).to_have_text()Element matches text
expect(locator).to_contain_text()Element contains text

3. Attributes & Properties

To check if an element has a given attribute with the expected value use to_have_attribute() and to check if an element has a specific class attribute (exact or one of multiple) use to_have_class.

expect(locator).to_have_attribute()Element has a DOM attribute
expect(locator).to_have_class()Element has a class property

4.State

To check if checkbox is checked use to_be_checked(), to check if the button to be clicked is enabled use to_be_enabled() and to check if the field is editable use to_be_editable()

expect(locator).to_be_checked()

Checkbox is checked

expect(locator).to_be_enabled()

Element is enabled

expect(locator).to_be_editable()

Element is editable

5. Count of Elements

To check if a list (or any container) has an exact number of children in Playwright.

expect(locator).to_have_count()

List has exact number of children

  1. URL and Title

To check the title in the page use to_have_title() and to check url in the page use to_have_url()

The above-mentioned assertions are some of the frequently used to verify the behavior of the page is correct. You can refer to more types of assertions in documentation in playwright

0
Subscribe to my newsletter

Read articles from Shalini Padmanabhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shalini Padmanabhan
Shalini Padmanabhan