What is the Page Object Model and when does it help?
Updated:
The Page Object Model (POM) is a design pattern for organizing automated user-interface tests. It groups code for finding fields, buttons, and performing actions in a screen object. The test uses those actions and checks the result. POM is particularly useful when the same interactions appear in several scenarios and each interface change requires fixes in many places.
Why copied steps complicate maintenance
Imagine a suite where the order, profile change, and billing tests all start with sign-in. Each scenario has its own field lookup, password entry, and button click. When developers change a field’s label, you have to find every copy. Some get updated, others retain the old lookup, and another gets a different waiting strategy.
The problem goes beyond line count. A new team member has to work out which procedure is correct and distinguish an application defect from a test-code defect when a test fails. Accumulated maintenance can contribute to a test suite becoming less useful to the team.
POM keeps knowledge of the interactions in one place. A test then calls something like signIn(email, password). If only the way a button is located changes, the fix may stay in the sign-in object. If sign-in starts requiring another step or the expected result changes, the affected scenarios need updating too. This is how the Selenium documentation describes the pattern.
What belongs in the object and what stays in the test
The object should describe what you can do on a particular screen: entering credentials, submitting a form, or reading an error message. Method names should explain the action. A reader learns more from submitOrder() than from clickButton3(). The method’s parameters and scope still need to be clear.
We recommend keeping the decision about what to verify in the test. A correct password should lead to the account, while an incorrect one should produce an error message. If a shared method checks for success internally on every sign-in attempt, it becomes difficult to use for a negative scenario. Likewise, if completeCheckout() hides delivery selection, payment, and result assertions, the test may no longer show which part of the process it checks.
Checking screen readiness is a different responsibility from verifying the expected test outcome. An object can wait for the form it needs to use. Selenium allows this check, and the Playwright POM example also checks visibility inside a helper method. Agree on a boundary within the team so objects do not hide individual scenarios’ expectations.
A simple Playwright example
The example has two versions with the same steps and outcome check. TypeScript uses Playwright Test. Python uses Playwright’s synchronous API and the pytest-playwright plugin, which supplies the test’s page object. The Playwright Python documentation also describes the page object pattern.
Both versions assume a test application with English field labels and a prepared account. Set baseURL in the Playwright Test configuration for TypeScript. For Python, set the base address with pytest --base-url https://test.example.test, as described in the pytest plugin reference. The addresses, labels and credentials are illustrative, so adapt them to your application. Save the Python test in a file such as test_product_filter.py. The outcome check uses Python web assertions.
The model catalogue at /products contains three products: two from Acme and one from another brand. The filter is a native <select> labelled Brand with an acme option value. After filtering, the list with data-testid="product-results" contains only matching products, each with one brand label marked data-testid="product-brand". Prepare the data before each test and restrict the list to these three products. A custom dropdown needs interactions appropriate to its elements, because select_option works with a native select.
Everything in one file
Sign-in, opening products, filtering and verifying the result are directly in the test. After selecting Acme, we check the filter value and both brand labels in the results. For one scenario, this is straightforward. Copying the same interactions into other tests increases the number of places needing repair.
# test_product_filter.py
from playwright.sync_api import Page, expect
def test_signed_in_user_can_filter_products_by_brand(page: Page) -> None:
page.goto("/sign-in")
page.get_by_label("Email", exact=True).fill("reader@example.com")
page.get_by_label("Password", exact=True).fill("example-password")
page.get_by_role("button", name="Sign in", exact=True).click()
expect(
page.get_by_role("heading", name="My account", exact=True)
).to_be_visible()
page.goto("/products")
brand_filter = page.get_by_label("Brand", exact=True)
product_brands = page.get_by_test_id("product-results").get_by_test_id(
"product-brand"
)
expect(product_brands).to_have_count(3)
brand_filter.select_option(value="acme")
expect(brand_filter).to_have_value("acme")
expect(product_brands).to_have_text(["Acme", "Acme"])
// tests/product-filter.spec.ts
import { test, expect } from '@playwright/test';
test('signed-in user can filter products by brand', async ({ page }) => {
await page.goto('/sign-in');
await page.getByLabel('Email', { exact: true }).fill('reader@example.com');
await page.getByLabel('Password', { exact: true }).fill('example-password');
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
await expect(page.getByRole('heading', { name: 'My account', exact: true }))
.toBeVisible();
await page.goto('/products');
const brandFilter = page.getByLabel('Brand', { exact: true });
const productBrands = page.getByTestId('product-results')
.getByTestId('product-brand');
await expect(productBrands).toHaveCount(3);
await brandFilter.selectOption({ value: 'acme' });
await expect(brandFilter).toHaveValue('acme');
await expect(productBrands).toHaveText(['Acme', 'Acme']);
});
A test and two page objects
We split the same scenario into a test and two objects. SignInPage controls the sign-in form. ProductPage has load_product_page() and filter_by_brand() methods, called loadProductPage() and filterByBrand() in TypeScript. Save each part in a separate file using the filename in its comment. For Python, also add an empty pages/__init__.py file and run pytest from the project root.
# pages/sign_in_page.py
from playwright.sync_api import Page
class SignInPage:
def __init__(self, page: Page) -> None:
self.page = page
def open(self) -> None:
self.page.goto("/sign-in")
def sign_in(self, email: str, password: str) -> None:
self.page.get_by_label("Email", exact=True).fill(email)
self.page.get_by_label("Password", exact=True).fill(password)
self.page.get_by_role("button", name="Sign in", exact=True).click()
# pages/product_page.py
from playwright.sync_api import Page
class ProductPage:
def __init__(self, page: Page) -> None:
self.page = page
self.brand_filter = page.get_by_label("Brand", exact=True)
self.product_brands = page.get_by_test_id("product-results").get_by_test_id(
"product-brand"
)
def load_product_page(self) -> None:
self.page.goto("/products")
def filter_by_brand(self, brand_value: str) -> None:
self.brand_filter.select_option(value=brand_value)
# test_product_filter.py
from playwright.sync_api import Page, expect
from pages.sign_in_page import SignInPage
from pages.product_page import ProductPage
def test_signed_in_user_can_filter_products_by_brand(page: Page) -> None:
sign_in = SignInPage(page)
products = ProductPage(page)
sign_in.open()
sign_in.sign_in("reader@example.com", "example-password")
expect(
page.get_by_role("heading", name="My account", exact=True)
).to_be_visible()
products.load_product_page()
expect(products.product_brands).to_have_count(3)
products.filter_by_brand("acme")
expect(products.brand_filter).to_have_value("acme")
expect(products.product_brands).to_have_text(["Acme", "Acme"])
// pages/sign-in-page.ts
import { type Page } from '@playwright/test';
export class SignInPage {
constructor(private readonly page: Page) {}
async open() {
await this.page.goto('/sign-in');
}
async signIn(email: string, password: string) {
await this.page.getByLabel('Email', { exact: true }).fill(email);
await this.page.getByLabel('Password', { exact: true }).fill(password);
await this.page.getByRole('button', { name: 'Sign in', exact: true }).click();
}
}
// pages/product-page.ts
import { type Page, type Locator } from '@playwright/test';
export class ProductPage {
readonly brandFilter: Locator;
readonly productBrands: Locator;
constructor(private readonly page: Page) {
this.brandFilter = page.getByLabel('Brand', { exact: true });
this.productBrands = page.getByTestId('product-results')
.getByTestId('product-brand');
}
async loadProductPage() {
await this.page.goto('/products');
}
async filterByBrand(brandValue: string) {
await this.brandFilter.selectOption({ value: brandValue });
}
}
// tests/product-filter.spec.ts
import { test, expect } from '@playwright/test';
import { SignInPage } from '../pages/sign-in-page';
import { ProductPage } from '../pages/product-page';
test('signed-in user can filter products by brand', async ({ page }) => {
const signIn = new SignInPage(page);
const products = new ProductPage(page);
await signIn.open();
await signIn.signIn('reader@example.com', 'example-password');
await expect(page.getByRole('heading', { name: 'My account', exact: true }))
.toBeVisible();
await products.loadProductPage();
await expect(products.productBrands).toHaveCount(3);
await products.filterByBrand('acme');
await expect(products.brandFilter).toHaveValue('acme');
await expect(products.productBrands).toHaveText(['Acme', 'Acme']);
});
Both objects use the same page, so they share one browser tab. The product object opens the page and sets the filter, while the test checks the expected value and result content. The to_have_text assertion with a list also checks the number of elements, so an empty result or a third product from another brand will fail. This example expects exactly two Acme labels.
POM adds code and files for a single test. The benefit becomes clearer when several scenarios use sign-in or filtering: shared interactions are repaired in the relevant object. The test retains its data and expectations. The sign-in action can also be used with an incorrect password, with a negative test checking the error.
Why a long script with repeated steps becomes hard to maintain
A standalone script can successfully perform sign-in and filtering. Maintenance becomes harder when the same locators, actions and waiting logic are copied into further scenarios. Each test then carries its own copy of the interface knowledge. As the suite grows, this approach can become substantially harder to maintain than shared page objects.
- Interface changes require fixes in several places. If the
Brandfield changes, you need to find every use. With POM, the shared interaction is inProductPage. - Copies gradually diverge. One test receives a new readiness check, another retains an old pause and a third uses a different element lookup. The same user action no longer follows a consistent procedure across the suite.
- The scenario gets buried in interaction details. In a long test, you have to separate intent from field lookups and clicks. Calls to
load_product_page()andfilter_by_brand()name the steps while expectations remain visible in the test. - A shared fix can remain incomplete. Fixing the first test does not mean every copy has been updated. With a shared method, you repair one implementation and then verify affected scenarios.
- Failure diagnosis takes more work. You need to compare which copy of the interaction ran and how it differs. Small named actions help narrow the investigation, but useful logs and traces are still needed.
- Several team members edit one large file. Changes to sign-in, products and payment within one script can overlap. Separate responsibilities help review, although shared objects still require change coordination.
Separating the scenario from page-specific knowledge is one of the benefits in the Selenium documentation. Organisation matters more than file count. A single file can also contain sensibly separated functions or classes.
Direct code may be sufficient for one short test. When interactions repeat and change, POM helps reduce the number of places needing repair. A poorly designed large class may merely move the complexity into another file. Separate specific responsibilities and preserve outcome assertions.
When to split a page into components
A whole-page object becomes difficult to follow when it handles navigation, a table, filters, and several unrelated dialogs. A repeated section of the interface can be separated into a component object and composed with the page object. Selenium describes this approach under Page Component Objects.
For example, a cart may contain several product rows with the same remove button. A row object looks for the button within a particular product. It should not automatically click the first button on the whole page. For navigation used on several screens, one component also prevents each page from containing its own copy of the navigation code.
Choose the boundary based on shared behavior and what changes together. Splitting an object just because its file exceeds a chosen line count can create unnecessary jumps between classes. Likewise, do not assume that two visually similar screens must inherit from a shared parent. Different permissions or forms may require separate behavior.
POM does not fix selectors, waiting, or data
A selector determines how a test finds an element. Moving a fragile lookup based on the order of nested elements into one class makes repairs easier, but the lookup remains fragile. Playwright recommends locators based on roles, labels, and agreed test identifiers. If several elements match, narrow the lookup to a particular form or component.
Semantic locators have conditions too. A button’s text may change when the application is translated, and the team needs to maintain test identifiers. Agree on whether the suite checks one language or several language versions, and which attributes form the testing interface. Changing a label may require a locator update even in a well-designed POM.
Tie waiting to an observable state. Playwright automatically checks interaction conditions and retries web assertions, but clicking an enabled button does not itself confirm that an order is complete. Wait for the outcome the scenario requires. A fixed pause may be too short in a slow environment and needlessly extend the run in a fast one.
Handle data separately. An isolated browser context separates individual tests’ cookies and storage, rather than the state of a shared server-side account. Two parallel tests can change the same cart even with separate browsers. Complement POM with prepared data and rules for accounts. Outages or uncontrolled changes in the test environment need addressing separately. For intermittent failures, first distinguish the cause using the flaky-test diagnosis procedure.
How to refactor an existing suite gradually
We recommend starting with one repeated process the team actually maintains. A shared function may be enough for a few simple tests. A POM class makes more sense when several actions and elements from one screen need to be grouped. Test count alone does not determine the right architecture.
- Find copies of the interactions for the chosen process and record what each scenario verifies. Also compare different accounts, permissions, and error paths.
- Run the affected tests before the refactor. Record existing intermittent failures separately so they are not later attributed to the structural change.
- Move element lookups and shared actions into a small object. Preserve test data and outcome checks until you verify the same behavior.
- Replace the original steps in one scenario and compare the result. Then update the other uses and remove unused copies.
- Verify successful and error paths where the suite covers them. Run tests individually and in the usual parallel mode, and check for differences.
During review, look at the tests calling the methods too. A method with many flags such as skipPayment or expectError may combine different procedures that would be clearer with separate names. Agreeing on responsibilities is more useful than requiring every test to have the same number of lines.
How to assess the benefit and choose the next step
After the refactor, check whether a routine locator change can be made in one place and whether the scenario still makes its purpose clear. Check a failed run too. The record should let you trace a particular action, rather than just an ambiguous failure in a large helper method. In Playwright, a recorded trace can help with this.
Track the scope of repairs during subsequent interface changes and the time needed to understand them. Shorter tests without preserved coverage are not an improvement. POM can reduce repeated maintenance, but it adds a shared layer that the team must be able to read and maintain.
Choose one frequently copied interaction, separate it from outcome assertions, and try it in representative scenarios. Decide whether to extend the approach to the rest of the suite based on readability, failure diagnosis, and the work needed when the application actually changes.