Encapsulating Locators in Page Objects
What you'll learn: How to centralize all UI selectors in Page Object properties so one DOM change doesn't ripple through dozens of tests.
The Problem with Scattered Selectors
When you write E2E tests directly against selectors, you end up with page.getByRole('button', { name: 'Submit Order' }) repeated across 15 different test files. The day your designer changes "Submit Order" to "Place Order," you hunt down every occurrence.
The Page Object Solution
Page Objects encapsulate all locators as properties. Instead of calling page.getByRole() directly in tests, you define the selector once in the Page Object:
class CheckoutPage {
constructor(page) {
this.page = page;
// Encapsulate all locators as properties
this.submitButton = page.getByRole('button', { name: 'Submit Order' });
this.emailInput = page.getByLabel('Email Address');
this.cardNumberInput = page.getByPlaceholder('1234 5678 9012 3456');
this.errorMessage = page.getByRole('alert');
}
async submitOrder() {
await this.submitButton.click();
}
}
Now your test references the property:
const checkout = new CheckoutPage(page);
await checkout.emailInput.fill('user@example.com');
await checkout.submitOrder();
Why This Matters
When the UI evolves—button text changes, inputs get new labels, or you refactor to use test IDs—you update one property declaration in the Page Object. Every test using that Page Object instantly adapts. No archaeological dig through test files.
Think of it like defining constants at the top of a file instead of magic strings throughout your code. Same principle, bigger payoff.
Key Takeaway: Encapsulate every CSS selector, role query, and text matcher as a Page Object property—your tests become resilient to UI refactoring, and maintenance shifts from tedious to trivial.