Page objects, kept thin
Why This Matters
By module 6 the example repository has the shop’s locators in a dozen files: getByTestId(/^product-\d+$/).filter({ hasText: … }).getByRole("button", { name: "Add to Cart" }) appears again and again. When the shop changes its markup, every one of those lines has to change. A page object puts each locator and user action in one place. Done well, tests get shorter and say what they test. Done badly, the page object becomes a second application nobody understands.
The shop as a page object
src/pages/ShopPage.ts in the example repository:
export class ShopPage {
readonly search: Locator;
readonly resultsCount: Locator;
readonly cartButton: Locator;
readonly productsError: Locator;
constructor(readonly page: Page) {
this.search = page.getByRole("textbox", { name: "Search for items" });
this.resultsCount = page.getByTestId("results-count");
this.cartButton = page.getByTestId("cart-button");
this.productsError = page.getByTestId("products-error");
}
async goto(): Promise<void> {
await this.page.goto("/shopping");
// Waiting for the page to be ready is part of "opening the shop", not a check of behaviour.
await expect(this.page.getByTestId("products-loading")).toBeHidden();
}
cards(): Locator {
return this.page.getByTestId(/^product-\d+$/);
}
card(name: string): Locator {
return this.cards().filter({ has: this.page.getByRole("heading", { name, exact: true }) });
}
async searchFor(text: string): Promise<void> {
await this.search.fill(text);
}
async addToCart(name: string): Promise<void> {
await this.card(name).getByRole("button", { name: "Add to Cart" }).click();
}
async openCart(): Promise<CheckoutDialog> {
await this.cartButton.click();
const dialog = new CheckoutDialog(this.page);
await expect(dialog.root).toBeVisible();
return dialog;
}
}
And the test that uses it, from tests/module-7/cart.spec.ts:
test("removing a product leaves the other one", async ({ checkoutWithTwo }) => {
await checkoutWithTwo.remove(9);
await expect(checkoutWithTwo.line(9)).toHaveCount(0);
await expect(checkoutWithTwo.line(5)).toBeVisible();
});
Three lines, all about the behaviour. Where the checkoutWithTwo comes from is lesson 32, after a deeper look at page objects in lesson 31.
What belongs in a page object
| In the page object | In the test |
|---|---|
Locators, named after what they are (cartButton, not blueButton) | What is expected |
Actions a user takes (addToCart, searchFor) | The data that matters to this test |
Waiting until a step is complete (openCart waits for the dialog) | Assertions about behaviour |
Returning the next page object (openCart returns a CheckoutDialog) |
The line is between doing and checking. openCart may wait for the dialog to appear, because “open the cart” is not done until it is open. Whether the cart shows the right total is a check, and it belongs in the test, where the reader sees it.
How thin is thin
Signs a page object is getting too fat:
- It asserts behaviour. A method
addToCartAndVerify()hides what is checked. When it fails, the test name says nothing about why. - It has a method for every test.
addHeadphonesAndLampAndOpenCart()is test data dressed up as a method. Compose small actions instead, or use a fixture. - It knows about other pages’ internals.
ShopPagereturns aCheckoutDialog; it does not reach into the dialog’s buttons. - It returns raw strings. Return locators, so the test can use web-first assertions on them (module 2). A method that returns
await locator.textContent()brings back the timing bug from module 3.
Page objects or helper functions?
A plain function is a fine alternative for one action:
async function addToCart(page: Page, name: string) { /* ... */ }
Use a class when several locators and actions belong together, as with the shop and the checkout. Use a function when it is one action shared by a few tests. Both are better than copying the same locator into ten files.
Real run
Running 5 tests using 5 workers
✓ 1 …ule-7/cart.spec.ts:27:1 › removing a product leaves the other one (3.4s)
✓ 2 …dule-7/cart.spec.ts:22:1 › increasing a quantity updates the line (3.5s)
✓ 3 …s:13:1 › the checkout total matches the catalogue prices plus tax (3.2s)
✓ 4 …art.spec.ts:33:1 › an order placed through the UI succeeds @smoke (3.4s)
✓ 5 …tests/module-7/cart.spec.ts:7:1 › search finds one product @smoke (3.8s)
5 passed (4.6s)
Exercise
The order test in tests/module-7/cart.spec.ts still fills the billing form with seven page.getByTestId("billing-…").fill(…) lines. Move that into CheckoutDialog as a method fillBilling(billing) that takes an object with the fields. What does the method take, and what does it not do?
Show suggested solution
export interface Billing {
firstName: string; lastName: string; email: string; phone: string;
address: string; city: string; zipCode: string;
}
async fillBilling(b: Billing): Promise<void> {
await this.root.getByTestId("billing-firstname").fill(b.firstName);
await this.root.getByTestId("billing-lastname").fill(b.lastName);
await this.root.getByTestId("billing-email").fill(b.email);
await this.root.getByTestId("billing-phone").fill(b.phone);
await this.root.getByTestId("billing-address").fill(b.address);
await this.root.getByTestId("billing-city").fill(b.city);
await this.root.getByTestId("billing-zipcode").fill(b.zipCode);
}
It takes the data as a parameter, so each test decides what to enter (valid data, a missing email, a very long name). It does not click Place Order and does not check anything: placing the order and checking the outcome stay in the test.