Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 35 ยท Test Structure

The Page Object Model

Learn the Page Object Model: one class per page, locators in one place, methods named after user actions, and returning the next page object to keep tests readable.

A first Selenium test is a list of low-level commands: find this field, type into it, find that button, click it. That is fine for one test. With fifty tests, the same locators are copied into every file. When a developer renames #login-btn to #sign-in, fifty tests break and you fix fifty places. The tests are also hard to read, because the story ("log in as Ada, open the cart") is buried under find_element calls.

The Page Object Model (POM) solves both problems. You write one class for each page (or large component) of the application. The class holds the locators and exposes methods named after what a user does: log_in(user, password), add_to_cart(). Tests then call those methods and never touch a locator. When the page changes, you edit one class.

The Python and Java snippets here are read-only because a real browser cannot run on this site. The runnable examples use a fake driver and a fake page in plain JavaScript. They are stand-ins: the page objects in them have exactly the same shape as real ones, but the "browser" is a small object that you can read in full.

Before: a test with everything inline

Here is a typical beginner test, in Python.

Python
# Read-only: no structure
def test_login_shows_dashboard(driver):
    driver.get("https://app.example/login")
    driver.find_element(By.ID, "email").send_keys("[email protected]")
    driver.find_element(By.ID, "password").send_keys("s3cret!")
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
    heading = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.TAG_NAME, "h1"))
    )
    assert heading.text == "Dashboard"

Count the problems. The locators are mixed with the story. Every other test that logs in repeats the same four lines. The wait is repeated too. If the login form gains a "remember me" checkbox, you search the whole suite for places to update.

The idea: pages as classes

One page, one class

Locators Kept together at the top of the class.
Actions Methods named like user tasks.
Queries Methods that read what the page shows.

The class hides how, the test says what.

1 / 2

A page object has three kinds of members.

  • Locators. Defined once, usually as class constants or private fields, so a change of markup is a one-line edit.
  • Actions. Methods that do something a user does. They wrap clicks, typing and the waits that go with them. A good action name describes intent (log_in), not mechanics (click_submit_button).
  • Queries. Methods that return what is on the page: a heading text, the list of error messages, the number of items in the cart.

What a page object should not do is assert. If a page object contains assert, one page object cannot be reused by a test that expects the opposite result. Keep assertions in the tests; let the page object return the facts they need.

After: the same test with page objects

Python
# Read-only: page objects for a real driver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class LoginPage:
    URL = "https://app.example/login"
    EMAIL = (By.ID, "email")
    PASSWORD = (By.ID, "password")
    SUBMIT = (By.CSS_SELECTOR, "button[type=submit]")
    ERROR = (By.CSS_SELECTOR, "[role=alert]")

    def __init__(self, driver):
        self.driver = driver

    def open(self):
        self.driver.get(self.URL)
        return self

    def log_in(self, email, password):
        self.driver.find_element(*self.EMAIL).send_keys(email)
        self.driver.find_element(*self.PASSWORD).send_keys(password)
        self.driver.find_element(*self.SUBMIT).click()
        return DashboardPage(self.driver)

    def error_message(self):
        wait = WebDriverWait(self.driver, 10)
        return wait.until(EC.visibility_of_element_located(self.ERROR)).text


class DashboardPage:
    HEADING = (By.TAG_NAME, "h1")

    def __init__(self, driver):
        self.driver = driver

    def heading_text(self):
        wait = WebDriverWait(self.driver, 10)
        return wait.until(EC.visibility_of_element_located(self.HEADING)).text


def test_login_shows_dashboard(driver):
    dashboard = LoginPage(driver).open().log_in("[email protected]", "s3cret!")
    assert dashboard.heading_text() == "Dashboard"

The test is now three short lines that read like a sentence. The By tuples are unpacked with * so that find_element(*self.EMAIL) becomes find_element(By.ID, "email"). In Java the same shape is a class with private final By email = By.id("email"); and methods that return the next page object.

The return-the-next-page pattern

Look at log_in: it returns a DashboardPage. That is the return-next-page (or fluent) pattern. An action that navigates returns the page object for wherever the user ends up. An action that stays on the page returns self (or nothing). The benefits:

  • Your editor autocompletes the next page's methods, so tests can chain: LoginPage(driver).open().log_in(...).open_cart().
  • The type of the return value documents the flow of the application.
  • A test cannot call a dashboard method on the login page by mistake.

When a failed login keeps the user on the login page, give the page two methods, for example log_in(...) returning DashboardPage and log_in_expecting_error(...) returning self. Two clear methods beat one method that returns different types depending on a flag.

flowchart LR
  T["Test"] --> L["LoginPage"]
  L -->|"log_in()"| D["DashboardPage"]
  D -->|"open_cart()"| C["CartPage"]
  L -.->|"locators and waits"| W["WebDriver"]
  D -.-> W
  C -.-> W

Tests talk to page objects; only page objects talk to the driver.

A page object you can run

The stand-in below builds a fake driver whose "page" is a small data object, then uses a real-looking LoginPage and DashboardPage on top of it. The test code at the bottom uses only the page objects.

JS Page objects on a fake driver

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

No output.

Both tests pass, and neither contains a locator. The class LoginPage is the only place that knows #email. If the real app renamed that field, you would edit one constant and rerun the tests.

Change one line, keep every test

The second stand-in makes the payoff visible. A suite of five tests logs in through the page object. The application "ships a redesign" that renames the submit button. We run the suite before the change, after the change with the old locator (everything breaks), and after fixing the single constant.

JS One locator change instead of five

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

No output.

Without the page object, you would have had five (in a real suite, hundreds of) copies of the locator to change. With it, you changed one line. That is the entire argument for the pattern in one picture.

Practical rules

  • One class per page or component. Large shared parts, such as a navigation bar or a modal, deserve their own component classes that page objects can hold.
  • Do not store elements. Keep locators in the class and look elements up inside methods. Stored WebElement objects become stale, as you saw in Why Tests Need Waits.
  • Put the waits inside the page object. An action should return only when the page is ready for the next step. Tests then stay free of timing code. See Implicit, Explicit and Fluent Waits.
  • Share a base class sparingly. A BasePage holding the driver and one or two wait helpers is useful. A deep inheritance tree is not.
  • Name methods after intent. add_to_cart() survives a redesign. click_blue_button() does not.
  • Do not wrap everything. A page object for a page you test once may be more ceremony than value. The pattern pays off where the same page appears in many tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of the Page Object Model?

    Page objects centralize locators and interaction details. When the markup changes, you update the page class instead of every test.
  2. 2. Where should assertions normally live?

    If a page object asserts, it can only be used by tests that expect that exact outcome. Returning data keeps page objects reusable.
  3. 3. A log_in method that navigates to the dashboard should return what?

    Returning the next page object documents the flow, enables chaining and gives you autocomplete for the new page's methods.
  4. 4. Why is storing a WebElement in a page object field a bad idea?

    A stored reference can point to a node that the page has replaced. Keeping the locator and finding the element inside each method avoids stale references.

Summary

  • A page object is a class with the locators of one page and methods that express what a user does there.
  • Tests call those methods; only page objects call the driver, so a UI change means one edit.
  • Actions that navigate return the next page object; others return self.
  • Keep assertions in tests, waits inside page objects, and locators (not elements) in fields.
  • Share only what you must in a base class, and name methods after intent.

Next: Selenium with pytest.