Manuals / Playwright with Python / Ch 13

Part 2 · Core InteractionsBeginner40 min read

7. Assertions with expect()

Playwright with Python · 244 pages source format

Playwright expect() auto-retries assertions until they pass or time out — pair it with locators instead of instant assert.

What you'll learn

  • expect(locator).to_be_visible()
  • Text, URL, and attribute asserts
  • Why expect beats bare assert

Retrying assertions

A bare assert page.title() == "…" fails immediately if the title hasn’t updated yet. expect() from playwright.sync_api keeps polling until the condition is true or the timeout expires — the same philosophy as auto-waiting for actions.

Use expect on locators for visibility, text content, CSS, and attributes. Use expect(page) for URL and title.

expect patterns
from playwright.sync_api import expect

expect(page.get_by_role("heading", name="Dashboard")).to_be_visible()
expect(page.get_by_text("Saved")).to_be_visible()
expect(page).to_have_url("**/dashboard")
expect(page).to_have_title("Dashboard")
Interactive study board
Retrying assertionsDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Page under testdrag · tap →Multi-browserdrag · tap →Automation pathdrag · tap →Tooling nodedrag · tap →
Clear?

Useful matchers

to_be_visible / to_be_hidden, to_have_text / to_contain_text, to_have_value, to_be_checked, to_have_attribute, to_have_count for lists. Soft assertions exist in some runners; with pytest you’ll usually fail fast on the first expect timeout — that’s fine for learning.

Do this now

Replace three raw asserts in your practice repo with expect().

Interactive study board
Useful matchersDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Page under testdrag · tap →Multi-browserdrag · tap →Automation pathdrag · tap →Tooling nodedrag · tap →
Clear?

Checklist