Software Testing & QA

End-to-End Testing with Playwright

40 min

E2E tests use the app like a person: open pages, click, type and check what appears. They catch JavaScript errors, broken layouts and wiring problems that other tests miss.

Setup

pip install pytest-playwright
playwright install chromium

A first E2E test

from playwright.sync_api import Page, expect

def test_visitor_can_send_contact_form(page: Page, live_server_url):
    page.goto(f"{live_server_url}/")
    page.get_by_label("Name").fill("Ada")
    page.get_by_label("Email").fill("ada@example.com")
    page.get_by_label("Message").fill("I need a booking website.")
    page.get_by_role("button", name="Send").click()
    expect(page.get_by_text("Thank you")).to_be_visible()

Stable selectors

Prefer selectors a user would recognise, in this order:

  1. get_by_role("button", name="Send")
  2. get_by_label("Email")
  3. get_by_text("Thank you")
  4. get_by_test_id("checkout-total") with data-testid attributes

Avoid CSS paths like div > div:nth-child(3) > button. They break whenever the layout changes. Role and label selectors also double as an accessibility check: if you cannot select it by role, screen readers may struggle too.

Avoiding flaky tests

  • Never use fixed sleeps. Playwright's expect(...) waits automatically until the condition is true or times out.
  • Make each test create its own data; do not depend on another test running first.
  • Reset state between tests (a fresh database or unique emails per test).
  • Run in CI with retries off at first, so you see flakiness and fix it rather than hide it.

Mobile, themes and languages

def test_mobile_tab_bar(browser):
    ctx = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True)
    page = ctx.new_page()
    page.goto(f"{BASE}/")
    expect(page.get_by_role("navigation", name="Mobile")).to_be_visible()

Also useful: color_scheme="dark", locale="he-IL" for right-to-left layouts, and page.screenshot(path=...) for visual review.

Debugging failures

pytest --headed --slowmo 300          # watch it run
PWDEBUG=1 pytest -k contact           # step through with the inspector
pytest --tracing retain-on-failure    # a full trace to open with `playwright show-trace`

Keep E2E focused

Cover the journeys that make money or trust: sign up and verify, log in with 2FA, buy a project, complete a learning module, send the contact form, admin approves a request. Leave edge cases to faster unit and integration tests.

Check yourself

  • Why are role-based selectors better than CSS paths?
  • What replaces fixed sleeps in Playwright?
  • Which journeys deserve E2E tests?

I tuoi progressi sono salvati solo in questo browser.

Invia per la revisione (10 punti)