Page objects in depth: components and composition
Why This Matters
The previous lesson kept page objects thin. Thin is necessary but not enough. As an application grows, the same parts show up on many pages: a product card in the shop, in search results and in a wishlist; a navigation bar everywhere; modals that open from anywhere. If every page object describes those parts again, you are back to copied locators, now hidden inside classes. This lesson splits pages into components, combines them by composition, and shows the designs that look tidy at first and hurt later.
Components: a root and everything inside it
A component object describes one part of the UI. It gets a root locator from whoever creates it, and finds everything else inside that root. This is src/pages/components/ProductCard.ts in the example repository:
export class ProductCard {
readonly name: Locator;
readonly prices: Locator;
readonly price: Locator;
readonly originalPrice: Locator;
readonly saleBadge: Locator;
readonly addButton: Locator;
readonly outOfStockButton: Locator;
constructor(readonly root: Locator) {
this.name = root.getByRole("heading");
this.prices = root.getByText(/^\$\d+\.\d{2}$/);
// Inside one card the order of the prices is part of its design, so nth() is safe here.
this.price = this.prices.nth(0);
this.originalPrice = this.prices.nth(1);
this.saleBadge = root.getByText("SALE", { exact: true });
this.addButton = root.getByRole("button", { name: "Add to Cart" });
this.outOfStockButton = root.getByRole("button", { name: "Out of Stock" });
}
async add(): Promise<void> {
await this.addButton.click();
}
async openDetails(): Promise<ProductDetail> {
await this.name.click();
const detail = new ProductDetail(this.root.page());
await expect(detail.root).toBeVisible();
return detail;
}
}
The ShopPage decides which card, and hands over the root:
card(name: string): Locator {
return this.cards().filter({ has: this.page.getByRole("heading", { name, exact: true }) });
}
product(name: string): ProductCard {
return new ProductCard(this.card(name));
}
Now one class describes all ten products:
test("a product on sale shows a badge and both prices", async ({ shop }) => {
const stand = shop.product("Smartphone Stand");
await shop.page.getByRole("button", { name: "Sort by Price" }).click();
await expect(stand.saleBadge).toBeVisible();
await expect(stand.price).toHaveText("$14.99");
await expect(stand.originalPrice).toHaveText("$19.99");
});
test("a product at full price has one price and no badge", async ({ shop }) => {
const lamp = shop.product("Desk Lamp");
await expect(lamp.prices).toHaveCount(1);
await expect(lamp.saleBadge).toHaveCount(0);
});
Two details from the locator lesson return here. The card is found by its heading, not with hasText, so “Wireless” does not also match the headphones. And nth() is fine inside the component: the order of the two prices within one card is part of the card’s design, not an accident of the data.
Locators are lazy, so components are cheap
Look at the first test again: it creates stand before it sorts by price. On the default page the Smartphone Stand is not even shown yet; it is on page 2 when the shop is sorted by name. That still works, because a locator is a description, not a search. Nothing is looked up until an action or an assertion uses it, and then it is looked up fresh.
That has three consequences:
- Building locators in a constructor costs nothing and needs no
await. - A component object stays valid when the page re-renders, re-sorts or navigates.
- Never store the result of a lookup (
await locator.textContent(), an element handle) in a page object. That is a snapshot that goes stale; a locator does not.
Composition, not a BasePage
Every page on the site has the same header navigation. The obvious design is a BasePage that all pages inherit from:
// Tempting, and the start of most unmaintainable frameworks
class BasePage {
constructor(readonly page: Page) {}
async goToWebElements() { /* ... */ }
async openCart() { /* ... */ }
async login(user: string) { /* ... */ }
async acceptCookies() { /* ... */ }
async waitForSpinner() { /* ... */ }
}
class ShopPage extends BasePage { /* ... */ }
Within months, BasePage holds everything that more than one page needs. Every page inherits every method, including those that make no sense on it: openCart() on the login page. And a change to BasePage can break any test.
Composition says what a page has instead of what it is:
export class SiteNav {
readonly root: Locator;
constructor(page: Page) {
// Scoped: the footer has links with the same names ("Web Elements", "API", "Shopping").
this.root = page.getByRole("navigation", { name: "Main navigation" });
}
link(name: string): Locator {
return this.root.getByRole("link", { name, exact: true });
}
async goTo(name: string): Promise<void> {
await this.link(name).click();
}
}
export class ShopPage {
readonly nav: SiteNav;
constructor(readonly page: Page) {
this.nav = new SiteNav(page);
// ...
}
}
test("the navigation is a component every page can have", async ({ shop }) => {
await shop.nav.goTo("Web Elements");
await expect(shop.page).toHaveURL(/\/webelements/);
});
A page that has no navigation simply does not get one. The scoping in SiteNav matters too: without the navigation landmark, getByRole("link", { name: "Web Elements" }) finds two links, one in the header and one in the footer.
Return the next object
An action that takes the user somewhere returns the object for where they are now:
test("the detail modal adds a product to the cart", async ({ shop }) => {
const detail = await shop.product("Ergonomic Chair").openDetails();
await expect(detail.name).toHaveText("Ergonomic Chair");
await expect(detail.savings).toBeVisible();
await detail.add();
await expect(shop.cartButton).toContainText("1 items");
});
openDetails() returns a ProductDetail, as openCart() returns a CheckoutDialog. The test never constructs page objects itself, and the type system tells you what you can do next. Note that openDetails() waits until the modal is visible: the action is not finished before that. Whether the modal shows the right product is a check, and it stays in the test.
Where to draw the boundaries
Follow the components the UI already has, not the pages:
| UI part | Object | Root |
|---|---|---|
| Header navigation | SiteNav | navigation “Main navigation” |
| One product in the grid | ProductCard | the card, by its heading |
| Product detail modal | ProductDetail | product-detail-modal |
| Checkout modal | CheckoutDialog | checkout-modal |
| The shop as a whole | ShopPage | the page; has a SiteNav, makes ProductCards |
If the developers use React, Vue or Angular, their component tree is a good guide: a <ProductCard> in their code is a ProductCard in yours. When the HTML gives a component a landmark role (article, dialog, navigation) and a name, its root locator is a role locator. The product card and the detail modal here have neither, so their roots use the test id. That is the same accessibility gap the locator lesson found.
Designs that hurt later
| Design | Why it hurts | Instead |
|---|---|---|
BasePage with shared methods | Every page inherits everything; one change breaks any test | Composition: a page has components |
A getter that returns await locator.textContent() | A snapshot that goes stale; no auto-waiting | Return the locator; assert in the test |
verifyCartTotal() in the page object | The check is hidden; the failure points at the page object | Expose total; expect(...).toHaveText() in the test |
One giant ShopPage with 60 locators | Nobody finds anything; merge conflicts | Split into the components the UI has |
A method per test (addHeadphonesAndLampAndOpenCart) | Test data dressed up as an API | Small actions, combined in a fixture (lesson 32) |
| Locators as CSS strings in a constants file | Loses role locators, chaining and filtering | Locator fields, built from a root |
When not to use page objects
For a suite of twenty tests against three pages, plain tests with a few helper functions are easier to read than a class hierarchy. Page objects pay off when the same UI is used by many tests, and when the UI changes often enough that one place to fix it matters. Start with plain tests. Extract a component the second time you copy a locator, not before.
Exercise
Write a Pagination component for the shop’s page buttons (<nav aria-label="Product pagination">). It needs locators for the previous button, the next button, a page button by number and the current page, plus a method goTo(n). Then write a test that goes to page 2 and checks that it is the current page and that “Previous page” is enabled.
Show suggested solution
export class Pagination {
readonly root: Locator;
readonly previous: Locator;
readonly next: Locator;
readonly current: Locator;
constructor(page: Page) {
this.root = page.getByRole("navigation", { name: "Product pagination" });
this.previous = this.root.getByRole("button", { name: "Previous page" });
this.next = this.root.getByRole("button", { name: "Next page" });
this.current = this.root.locator('[aria-current="page"]');
}
page(n: number): Locator {
return this.root.getByRole("button", { name: `Page ${n}`, exact: true });
}
async goTo(n: number): Promise<void> {
await this.page(n).click();
}
}
test("page 2 becomes the current page", async ({ shop }) => {
const pagination = new Pagination(shop.page); // or a `pagination` field on ShopPage
await pagination.goTo(2);
await expect(pagination.current).toHaveAccessibleName("Page 2");
await expect(pagination.previous).toBeEnabled();
});
exact: true keeps Page 1 from matching Page 10 once the shop has ten pages. current uses aria-current, which is how the site marks the active page for screen readers; role locators have no option for it, so a CSS attribute selector inside the scoped root is the honest choice. goTo does not check anything, and the test asserts on locators.