Notes
The problem
Without page objects, every test that searches contains the search box locator. Some use the role, one uses the id, and nobody knows which is right. When the label changes, you edit twenty three files. And the tests read as a list of clicks and fills, so a reader has to work out what behaviour is being tested. Both problems grow with every test you add.
test A: getByRole("searchbox",
{name: "Search products"})
test B: getByRole("searchbox",
{name: "Search products"})
test C: locator("#q") (!)
...
label renamed to "Search"
→ 23 tests to edit
tests read like clicks, not
like behaviour The idea
The idea is simple. Create a class for each page, or each significant part of a page. It owns the locators for that page and offers methods for what a user can do there: search for a term, add a product to the cart. Tests call those methods and check results. When the UI changes, you fix one class. Tests describe what the user does; page objects know how it is done on this particular page.
- a class per page (or part) owns its locators offers user actions: searchFor(term), addToCart
- tests call actions and assert on results
- UI changes → fix one class
- tests: WHAT; page objects: HOW
ShopRung ProductsPage
Here is a real ShopRung products page object. The constructor receives the page and defines locators once: the search box by role and label, and the result count by test id. Search for fills the box and presses Enter, which submits the search form. Locators in Playwright are lazy, they do not search until used, so defining them in the constructor is cheap and safe even before the page loads.
export class ProductsPage {
readonly search: Locator;
readonly count: Locator;
constructor(private page: Page) {
this.search = page.getByRole(
"searchbox", {name: "Search ..."});
this.count = page.getByTestId(
"result-count"); }
async searchFor(term: string) {
await this.search.fill(term);
await this.search.press("Enter"); } Parameterised parts
Lists need parameterised locators. Card takes a product name and returns the product card containing it, so tests can check one card. Add to cart finds that card's button and clicks it. Open goes to the products page. Notice the methods speak the user's language, product names, never CSS paths or indexes, and the scoping trick from the locators episode now lives in one place.
card(name: string) {
return this.page
.getByTestId("product-card")
.filter({ hasText: name });
}
async addToCart(name: string) {
await this.card(name)
.getByRole("button").click();
}
async open() {
await this.page.goto("/"); } } The test
Now the test reads like the behaviour. Open products, search for mug, expect the count to be two products, and expect the red build mug's card to say out of stock. We ran it against ShopRung, and it passed. If the search label changes tomorrow, only the page object changes, and every test that searches keeps working.
test("search finds the two mugs",
async ({ page }) => {
const products =
new ProductsPage(page);
await products.open();
await products.searchFor("mug");
await expect(products.count)
.toHaveText("2 products");
await expect(products.card(
"Red Build Mug"))
.toContainText("Out of stock"); }); Where assertions go
Where do assertions go? A common, useful rule: page objects hold locators and actions, and perhaps a check that the right page is open. Tests hold the expectations, because one page object serves many tests that expect different things: two results in one test, none in another. So expose locators or values from the page object, like count or card, and let the test assert on them.
- page objects: locators and actions, maybe "am I here?" checks
- tests: the expectations (what SHOULD happen)
- why: one page object serves many tests with different expectations
- expose locators or values; let the test assert
Components
Real pages share parts. ShopRung's header, with the search box, cart count and log in link, appears on every page, so it becomes its own component object, and both the products page and the cart page have a header. Actions that navigate can return the next page object: header open cart returns a cart page, giving a fluent flow. Prefer this composition over long base page inheritance chains.
- Header: search, cart count, log in / out ProductsPage has a Header
- CartPage has a Header
- actions that navigate can return the next page: header.openCart() → CartPage
- prefer composition over deep inheritance (BasePage chains)
In Java
In Java with Selenium the pattern is identical. The class holds the driver and its By locators as private fields, and public methods for actions, often returning this or the next page object for fluent chains, plus methods that return values for tests to assert on, like the count text. Avoid the old page factory annotations for new code; plain By fields with explicit waits are clearer.
public class ProductsPage {
private final WebDriver d;
private final By search =
By.id("q");
private final By count = By
.cssSelector("[data-testid=
result-count]");
public ProductsPage searchFor(
String term) { ...; return this; }
public String countText() {
return d.findElement(count)... The limits
The pattern has limits. Page objects can grow into god objects with two thousand lines. Deep base page inheritance hides behaviour. Wrapping every trivial click adds code without value. Hidden assertions inside actions surprise readers. And flows that span many pages fit pages poorly. Alternatives exist: small helper functions, Playwright fixtures, which is the next episode, and the screenplay pattern, which models actors and tasks instead of pages.
- god objects: 2,000-line pages
- deep BasePage inheritance
- every click wrapped, even trivial ones
- assertions hidden inside actions
- pages for flows that span many pages
- alternatives: small helpers, fixtures, screenplay pattern
Common mistakes
Page object mistakes. Locators still duplicated in tests anyway. Methods named after clicks, like click button three, instead of behaviour, like apply coupon. A static shared driver inside pages, which breaks parallel runs. Waits sprinkled in tests instead of inside page methods. One page object per test, which defeats the purpose. And returning raw elements everywhere, so tests depend on the DOM again.
- locators duplicated anyway
- methods named after clicks (clickButton3) not behaviour
- static driver inside pages
- waits sprinkled in tests
- one page object per test
- returning raw WebElements everywhere
Say it like this
In the interview: the Page Object Model is a design pattern where each page or component is a class that owns its locators and offers user level actions. Tests call those actions and make the assertions, so tests read like behaviour and UI changes are fixed in one place. I keep assertions in tests, compose shared components like headers, return the next page from navigation, and avoid god objects and deep inheritance.
- "A design pattern where each page or component is a class
- that owns its locators and offers user-level actions.
- Tests call those and assert, so they read like behaviour and UI changes are fixed once. I
- keep assertions in tests, compose components, and avoid
- god objects and deep
- inheritance."