Assertions verify that your tests produce expected results. Playwright provides two assertion styles: pytest assertions and Playwright’s web-first expect() assertions. Each has specific use cases and advantages.
# Contains specific textexpect(cart_page.cart_badge).to_contain_text("2")# Exact text matchexpect(page.locator("h1")).to_have_text("Products")# Text matches regexexpect(page.locator(".price")).to_have_text(/\$\d+\.\d{2}/)
to_contain_text() is case-sensitive. Use .lower() or regex patterns for case-insensitive matching.
# Check button colors before and after clickingexpect(page.locator('[data-test="add-to-cart-sauce-labs-backpack"]')).to_have_css( "color", "rgb(19, 35, 34)")expect(page.locator('[data-test="add-to-cart-sauce-labs-backpack"]')).to_have_css( "background-color", "rgb(255, 255, 255)")page.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click()# After clicking, button color changesexpect(page.locator('[data-test="remove-sauce-labs-backpack"]')).to_have_css( "color", "rgb(226, 35, 26)")
Common CSS Properties to Test
color: Text color (use RGB format)
background-color: Background color
display: Element display type (block, flex, none, etc.)
# Element is enabledexpect(page.locator("#submit-button")).to_be_enabled()# Element is disabledexpect(page.locator("#submit-button")).to_be_disabled()
# Checkbox is checkedexpect(page.locator("#agree-terms")).to_be_checked()# Checkbox is uncheckedexpect(page.locator("#agree-terms")).not_to_be_checked()
# Element has focusexpect(page.locator("#username")).to_be_focused()
# Element is editableexpect(page.locator("#comment")).to_be_editable()# Element is read-onlyexpect(page.locator("#locked-field")).not_to_be_editable()
# Has specific attribute valueexpect(page.locator("a")).to_have_attribute("href", "/login")# Attribute contains valueexpect(page.locator("input")).to_have_attribute("class", /form-control/)# Has attribute (any value)expect(page.locator("img")).to_have_attribute("alt")
# Input has specific valueexpect(page.locator("#username")).to_have_value("standard_user")# Empty inputexpect(page.locator("#search")).to_have_value("")# Using pytestassert page.locator("#email").input_value() == "[email protected]"
# Element should NOT be visibleexpect(page.locator(".error")).not_to_be_visible()# Text should NOT be presentexpect(page.locator("h1")).not_to_contain_text("Error")# Element should NOT have classexpect(page.locator("button")).not_to_have_class("disabled")# Using pytestassert "error" not in page.urlassert not error_message.is_visible()
# Wait up to 10 secondsexpect(page.locator(".slow-loading")).to_be_visible(timeout=10000)# Wait only 1 secondexpect(page.locator(".fast-element")).to_be_visible(timeout=1000)