Playwright + TS · Lesson 24 of 36
Module 24: Page Object Model (POM)
Try it yourself
Implement CartComponent:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
Without POM, when a login button selector changes, you must update 50 different test files. With POM:
// pages/BasePage.ts
import { Page, Locator } from "@playwright/test";
export abstract class BasePage {
constructor(protected readonly page: Page) {}
public async navigateTo(path: string): Promise<void> {
await this.page.goto(path);
}
public async waitForPageLoad(): Promise<void> {
await this.page.waitForLoadState("domcontentloaded");
}
}// pages/LoginPage.ts
import { Page, Locator, expect } from "@playwright/test";
import { BasePage } from "./BasePage";
export class LoginPage extends BasePage {
// 1. Declare Locators as readonly properties
private readonly usernameInput: Locator;
private readonly passwordInput: Locator;
private readonly loginButton: Locator;
private readonly errorMessage: Locator;
constructor(page: Page) {
super(page);
this.usernameInput = page.getByLabel("Username");
this.passwordInput = page.getByLabel("Password");
this.loginButton = page.getByRole("button", { name: "Sign In" });
this.errorMessage = page.getByRole("alert");
}
// 2. High-level business actions
public async login(user: string, pass: string): Promise<void> {
await this.usernameInput.fill(user);
await this.passwordInput.fill(pass);
await this.loginButton.click();
}
// 3. Status checks
public async expectErrorMessage(message: string): Promise<void> {
await expect(this.errorMessage).toContainText(message);
}
}login(user, pass), addItemToCart(item)). Locators are private.clickUsername(), clickPassword()).Welcome to Phase 4! We begin with the Page Object Model, the gold standard design pattern for maintainable automation. In this lesson, you will learn how to build strongly-typed BasePage classes, encapsulate locators as private properties, compose reusable Component Objects, and separate user actions from assertions. Let's architect clean page objects!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
It is a best practice to keep tests responsible for assertions (e.g. expect(dashboard.isLoaded()).toBe(true)), or provide specialized assertion helper methods on the POM (e.g. expectErrorMessage). Avoid mixing business assertions inside navigation methods.
Yes! BasePage holds common elements like header, footer, and navigation methods, which child pages inherit using TypeScript 'extends'.
Finished reading?
Review the worked example in the editor, then mark the lesson complete.