Page Object Model in Playwright: Step-by-Step Guide
The Maintenance Challenge
Imagine having 100 test files. If the login form's "Email" input selector changes from #email to #user-email, you would have to edit 100 files. This is unsustainable.
The Page Object Model (POM) is a design pattern that abstracts page structures away from test cases. You represent each webpage (or modal/widget) as a class, storing its selectors and action helper methods inside that class. If a selector changes, you update it in exactly one file.
Step 1: Creating a POM Class
In Playwright, a POM class receives the active Page instance in its constructor. Let's create a login page object:
// pages/LoginPage.ts
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly submitButton: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByPlaceholder('Enter your email');
this.passwordInput = page.getByPlaceholder('Enter your password');
this.submitButton = page.getByRole('button', { name: 'Log In' });
}
async navigate() {
await this.page.goto('https://playwrightpad.in/login');
}
async login(email: string, pass: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(pass);
await this.submitButton.click();
}
}
Step 2: Implementing POM inside Tests
To use this page object inside your test files, simply import the class, instantiate it with the test's page instance, and call its methods:
// specs/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
test('successful authentication with page objects', async ({ page }) => {
const loginPage = new LoginPage(page);
// Navigate to login page
await loginPage.navigate();
// Call page object helper action
await loginPage.login('[email protected]', 'SecurePassword123');
// Verify assertion
await expect(page).toHaveURL(/.*lobby/);
});
Conclusion
Page Object Models are essential for scaling E2E automation structures. They enforce code reuse, separate layout definitions from business logic, and reduce test maintenance overhead. Want to generate Page Objects automatically? Try our free POM Generator Tool!
Related Guides
Complete Playwright Tutorial for Beginners (2026)
New to test automation? This step-by-step Playwright tutorial walks you through setting up Playwright, writing your first E2E script, and executing it.
Read GuideMastering Playwright Locators: The Complete Guide
Locators are the building blocks of reliable automation tests. Learn how to write resilient selectors that stand the test of page redesigns.
Read Guide10 Playwright Best Practices for Reliable Tests
Tired of debugging failing builds? Follow these 10 Playwright best practices to write stable, maintainable, and lightning-fast test suites.
Read Guide