Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Web / API / Mobile · Chapter 02 / 04

Test automation learning path

Web UI with Playwright

Auto-waiting, locator strategy, page objects, reusing signed-in state and network fault injection.

Auto-waiting, and why sleeps are banned

Retrying assertions wait for a state; a fixed sleep guesses, and guessing is the main source of UI flake.

Modern browser automation waits automatically before acting: it checks that an element is attached, visible, stable, able to receive events and enabled, and reports which condition was not met if the timeout expires. The matching idea on the assertion side is a retrying expectation, which re-evaluates until it passes or the timeout runs out. This distinction causes more flakiness than any other single thing in browser suites. Reading a value and comparing it with a plain assertion is a single-shot check that races the application, whereas the retrying form waits for the value to arrive. Anyone arriving from an older tool tends to write the racing version out of habit. A fixed sleep is worse than both: when it is long enough it wastes time on every run, and when the machine is loaded it is still too short. What you actually need is never a duration but a state, and the best state is one the application publishes deliberately — a flag set when rendering completes is a reasonable thing to ask developers for.

Key points

  • Actions auto-wait for attached, visible, stable, event-ready and enabled before proceeding
  • Retrying assertions wait for a value; reading and comparing with plain assert races the application
  • Never sleep for a duration — wait for a state, ideally one the application publishes deliberately

Code

# Races the application: reads once, compares once.
assert page.get_by_test_id("cart-count").inner_text() == "1"

# Waits for the state to arrive, then passes.
expect(page.get_by_test_id("cart-count")).to_have_text("1")

# Never this. When it works it is slow; when the machine is loaded it still fails.
time.sleep(2)


# Best of all: the application publishes a deterministic readiness signal, and
# the page object waits on that instead of on anything time-based.
class ProductsPage(BasePage):
    ready_locator = "[data-testid=product-grid][data-loaded=true]"

    def search(self, term: str):
        self.search_input.fill(term)
        self.testid("apply-filters").click()
        expect(self.testid("product-grid")).to_have_attribute("data-loaded", "true")
        return self

Asking developers for a readiness attribute removes a whole class of flakiness permanently.

See it in the framework

  • Implementation · Wait-until-ready helper: framework/web/base_page.py — live · reviewed
  • Used by · Used by: tests/web/test_shopping_flow.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Reading text into a variable and asserting on it, which is a single-shot check that races the page
  • Waiting for a spinner to disappear and treating that as data rendered — the gap between them is where flakes live

Practice exercise

Search a UI suite for sleep calls. For each one, work out which state it was waiting for and replace it with a retrying assertion on that state. Where no such state exists, write down what you would ask developers to expose.

Locator strategy for the web

Prefer role, then test id; scope lookups to a parent; treat generated class names and XPath as last resorts.

Locator choice determines how often a redesign breaks a suite. The best first choice is a role-based lookup, because it addresses an element the way a person or a screen reader perceives it — a button named Log in — which also makes it a free accessibility signal, since anything the role query cannot find is equally invisible to assistive technology. The second choice is a dedicated test identifier attribute, which nothing in a redesign can break and no stylesheet rename can disturb; configure which attribute name your tools read in one place so switching conventions is a single edit. Label, placeholder and text lookups are good for forms and content but couple tests to wording that marketing will eventually change. Generated class names and structural paths through nested elements are the worst options, and anything containing a positional index is guaranteed to break as soon as sorting or data changes. Scoping a lookup to a parent element expresses the real relationship and survives another matching element appearing elsewhere.

Key points

  • Role-based lookups address elements as a user perceives them and double as an accessibility signal
  • A dedicated test id attribute is the only selector a redesign cannot break; configure its name once
  • Scope lookups to a parent; never use a positional index or a generated class name

Code

# Best first: how a person and a screen reader perceive the control.
page.get_by_role("button", name="Log in")

# Second: an attribute that exists purely so tests have a stable handle.
playwright.selectors.set_test_id_attribute("data-testid")   # configured once
page.get_by_test_id("submit")

# Scoped lookup expresses the real relationship and survives duplicates.
row = page.get_by_test_id("cart-row").filter(has_text="Aurora Headphones")
row.get_by_test_id("remove").click()

# Never:
#   page.locator(".css-1x2y3z")                      generated, changes per build
#   page.locator("div > div > div:nth-child(3)")     structural and positional
#   page.locator("(//button)[3]")                    index-based

Scoped, semantic locators; the commented block lists what a redesign will break within a sprint.

See it in the framework

  • Implementation · Locator helpers (testid/role): framework/web/base_page.py — live · reviewed
  • Used by · Locators in use: framework/web/pages.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Selectors built from generated class names, which change on every build of a styled component library
  • Copying a selector out of a browser's inspector, which produces long structural paths that break constantly

Practice exercise

Rewrite one test using only role-based locators. List the elements you could not reach — each of those is an accessibility finding worth raising, not just a testing inconvenience.

Reusing signed-in state and seeding through the API

Log in once and inject the saved state; build preconditions through the API rather than by clicking.

Logging in through the form in every test is usually the single largest waste in a browser suite, and it has a second cost: when login breaks, every test fails at once and the signal is buried. The fix is to sign in once per constraint, not once for the whole suite, and inject the saved state into each new browser context. The constraint is whether tests mutate shared server-side state: if every test only reads (browses, searches), one shared account and one saved state file is enough. If tests write — add to cart, place an order, change a profile — sharing that account under parallel execution means workers stomp on each other's data, so give each parallel worker its own account and its own saved state file instead (a worker account plus one storage-state file per worker id is the shape that survives running with multiple workers). Either way, keep a small set of tests that exercise the login form itself — the happy path, plus whatever negative cases matter for this product (wrong password, expired session, wrong role) — everything else injects the saved state and skips the form. Authenticate through the real form when capturing the state rather than injecting a hand-made token, because the saved state then reflects everything a genuine login produces and will not drift the day authentication changes. The same principle applies to data. Clicking through five screens to reach the screen under test is slow and couples every test to every screen, so build the precondition through the API and use the browser only for the step you are actually verifying. One detail decides whether this works: the API fixture and the browser must be the same account, or the page will render something the fixture never created.

Key points

  • Share one saved login state only when tests don't mutate shared server-side state; parallel tests that write (cart, orders, profile) need one account and one state file per worker
  • Keep the login form itself under test — the happy path plus whatever negative cases matter (bad password, expired session, wrong role) — not just one test
  • Build preconditions through the API and verify through the UI — but use the same account for both

Code

@pytest.fixture(scope="session")
def storage_state(browser, base_url, worker_account, worker_id) -> str:
    # One state file per worker: a shared path means four processes writing
    # the same file at the same time.
    state_path = ARTIFACTS / f"storage_state.{worker_id}.json"
    username, password = worker_account

    context = browser.new_context(base_url=base_url)
    LoginPage(context.new_page()).open().login(username, password)
    context.storage_state(path=str(state_path))
    context.close()
    return str(state_path)


def test_removing_an_item_updates_the_total(app_as_user, api_seed):
    api_seed.cart.clear()                        # arrange via API, about 20 ms
    product = api_seed.products.first_in_stock()
    api_seed.cart.add_item(product.id, 2)

    cart = app_as_user.cart.open()               # act and assert via the UI
    cart.remove(product.name)

    approx_money(cart.total, 0.0)

api_seed authenticates as the same worker account the browser uses, so the page shows what it created.

See it in the framework

  • Implementation · Per-worker storage-state fixture: tests/web/conftest.py — live · reviewed
  • Used by · Login test: tests/web/test_login.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Writing one shared state file from several parallel workers at once, which corrupts it
  • Seeding data as one user while the browser is signed in as another, so the page renders nothing the fixture created
  • Treating "one login test" as a hard rule — negative auth, session expiry, and role/permission checks are legitimate additional login-form tests, not violations of the shortcut

Practice exercise

Convert a UI suite that logs in per test to shared signed-in state, and measure the runtime before and after. Then move one test's setup from clicking to an API call and measure again.

Network interception: testing the error paths

Route interception reaches the failure branches QA normally cannot produce — and they are usually broken.

Modern browser tools can intercept requests, which unlocks the branches a UI suite normally cannot reach. Server errors, timeouts, empty collections, malformed payloads and offline states are almost never exercised manually because producing them requires cooperation from a backend, and as a result they are almost always broken — a spinner that never stops, an error swallowed silently, a blank screen where a message belongs. Fulfilling a route with a chosen status and body turns each of those into a short, deterministic test. Latency injection is equally valuable and rarely used: delaying a response surfaces missing loading states and races that a fast office connection hides entirely. Two cautions keep this technique honest. Intercept only what you are deliberately faking, since mocking everything produces a test that passes while the real integration is broken. And when you assert on the error state, assert on what the user actually sees, because a test that passes while the screen is blank is worse than no test.

Key points

  • Fulfilling a route with a chosen status turns unreachable error branches into short deterministic tests
  • Latency injection surfaces missing loading states that a fast connection hides completely
  • Intercept only what you deliberately fake, and assert on what the user actually sees

Code

def test_api_failure_is_surfaced_to_the_user(app_as_user):
    page = app_as_user.page
    page.route(
        "**/api/cart/items",
        lambda route: route.fulfill(
            status=500,
            content_type="application/json",
            body='{"detail":"Internal error"}',
        ),
    )

    products = app_as_user.products.open()
    products.cards[0].add_to_cart()

    # The requirement: fail visibly, never silently.
    expect(products.status).to_contain_text("Internal error")
    expect(products.status).to_have_class("error")


# Also available and rarely used:
#   context.set_offline(True)            the mobile-specific failure mode
#   route.abort()                        a dropped request
#   a route handler that sleeps first    latency injection

Five lines cover a branch most suites never reach, and the assertion is on what the user sees.

See it in the framework

  • Used by · Fault-injection tests: tests/web/test_shopping_flow.py — live · reviewed
  • Web layer notes: docs/04-web.md — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Mocking so much of the network that the test would still pass if the backend were deleted
  • Asserting on an internal flag rather than the visible message, so the test passes while the user sees nothing

Practice exercise

Pick a screen you know and write three tests against it: the API returning an empty collection, a server error, and a two-second delay. At least one will probably reveal a genuine gap in the interface.

Source registry

8 chapter references
Playwright assertions

Auto-retrying expect() assertions and their timeouts

Microsoft · Official documentation
Source ↗
Playwright for Python

Browser automation, contexts, auto-waiting and the pytest plugin

Microsoft · Official documentation
Source ↗
Eradicating Non-Determinism in Tests

Root causes of non-deterministic tests and how to remove rather than mask them

martinfowler.com · Industry article
Source ↗
Playwright locators

Locator strategies, role-based queries and test ids

Microsoft · Official documentation
Source ↗
axe-core rule descriptions

Which accessibility rules are automatable, and their impact levels

Deque Systems · Official documentation
Source ↗
Playwright authentication

Reusing signed-in state across tests with storage state

Microsoft · Official documentation
Source ↗
qa-automation-python reference framework

The runnable framework and demo application every lesson in this path is drawn from

sergiiiavt · Reference implementation
Source ↗
Playwright network interception

Routing, mocking and fault injection at the network layer

Microsoft · Official documentation
Source ↗