Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Page Objects and UI Tests

Component Objects, Waits and Stable Locators

Split big page objects into component objects, choose stable locators, and use explicit waits instead of sleeps so Cucumber UI scenarios stop being flaky.

Page objects solve the first problem of UI tests: knowledge about markup in the wrong place. Two problems come next. Pages grow, and soon one class holds fifty locators for headers, menus, forms and dialogs. And pages are asynchronous: the button you want is not there yet, so the test clicks nothing and fails, but only sometimes. This lesson handles both with component objects and waits, and ends with advice on choosing locators that survive redesigns.

The real Selenium examples are read-only, because browsers do not run on this site. The runnable examples are plain Java stand-ins: a component tree, and a polling wait that you can watch succeed and time out.

Component objects

A component object is a page object for a part of a page that appears in many places or has its own logic: a navigation bar, a product card, a data table row, a modal dialog, a date picker. The component wraps a root element and finds its children relative to it, so you can have many instances on one page.

Java
public class ProductCard {
    private final WebElement root;

    public ProductCard(WebElement root) { this.root = root; }

    public String title() {
        return root.findElement(By.cssSelector("[data-testid=title]")).getText();
    }

    public String price() {
        return root.findElement(By.cssSelector("[data-testid=price]")).getText();
    }

    public void addToCart() {
        root.findElement(By.cssSelector("[data-testid=add]")).click();
    }
}

public class SearchResultsPage {
    private final WebDriver driver;

    public SearchResultsPage(WebDriver driver) { this.driver = driver; }

    public List<ProductCard> cards() {
        return driver.findElements(By.cssSelector("[data-testid=product-card]"))
                     .stream().map(ProductCard::new).toList();
    }

    public ProductCard cardWithTitle(String title) {
        return cards().stream()
                .filter(c -> c.title().equals(title))
                .findFirst()
                .orElseThrow(() -> new NoSuchElementException("No card titled " + title));
    }
}

The page object holds navigation and lists; the component holds the details of one card. A step reads like the scenario:

Java
@When("she adds {string} to the cart")
public void add(String title) {
    results.cardWithTitle(title).addToCart();
}

The next stand-in models the same structure with a tiny tree of fake elements. Notice how cardWithTitle searches by what the user sees, not by position.

Java A component object over a fake page (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Waits: never sleep

Web pages update after the browser finishes loading: scripts fetch data, animations finish, spinners vanish. A test that acts too early fails. The tempting fix is Thread.sleep(5000). It is wrong twice: it wastes five seconds when the page was ready after one, and it still fails on a slow day.

Selenium offers three kinds of wait:

Wait What it does Verdict
Implicit every findElement retries for a global time simple, but hides problems and mixes badly with explicit waits
Explicit (WebDriverWait) waits for a condition you name, up to a timeout the recommended default
Fluent explicit wait with custom polling interval and ignored exceptions for special cases
Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement banner = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-testid=welcome]")));

wait.until(ExpectedConditions.elementToBeClickable(By.id("pay"))).click();

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".spinner")));

Waits belong inside page objects, so steps never mention timing. A method like waitForResults() or a click helper that waits for clickability keeps all synchronization in one place. Playwright builds this in (auto-waiting before actions), which is one reason many teams find it less flaky.

Here is a polling wait in plain Java. It re-checks a condition every 50 ms until it is true or the timeout expires, and reports how long it really waited. The simulated page becomes ready after a random-looking but fixed delay.

Java A polling wait (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A fixed sleep could not tell you the first case finished early. A wait returns as soon as the condition holds, so a fast page makes a fast test and a slow page still passes.

Stale elements

If the page re-renders, an element you looked up earlier may be detached, and using it throws StaleElementReferenceException. Look the element up again right before using it, and let your page object methods find elements on demand rather than keeping them in fields for a long time.

Stable locators

From most to least stable:

  1. Dedicated test attributes: data-testid="checkout-button". Ask developers to add them; they never change for styling reasons.
  2. Ids and accessible names (labels, roles, aria-labels). These also push the product toward better accessibility.
  3. Meaningful CSS such as form#login input[name=email].
  4. Link or button text, if the text is part of the behavior (and mind translations).
  5. XPath by position (//div[3]/span[2]) and generated class names (.css-1x9fz) are fragile; avoid them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a component object?

    Component objects model parts of a page and find their children relative to their root element.
  2. 2. Why is Thread.sleep(5000) a poor wait?

    A fixed sleep is both too long and too short. Explicit waits return as soon as the condition holds.
  3. 3. Which locator is generally the most stable?

    Dedicated test attributes are not changed by styling or layout edits.
  4. 4. Where should wait logic live?

    Putting synchronization in page objects keeps steps free of timing details.

Summary

  • Split large pages into component objects wrapped around a root element and find children relative to it.
  • Use explicit waits for named conditions; avoid fixed sleeps and be careful mixing implicit with explicit waits.
  • Put synchronization in page and component objects, and re-find elements to avoid stale references.
  • Prefer data-testid, ids and accessible names over positional XPath and generated classes.

Next: API and service-layer tests