📄 Playwright Essentials #40 Page Object Model: Creating Pages in Playwright
In this episode, we dive into the Page Object Model (POM) pattern in Playwright—starting with how to create page classes that encapsulate locators and actions. POM helps you write clean, maintainable, and reusable test code by separating UI logic from test logic. Whether you're testing login flows, dashboards, or checkout pages, this structure is essential for scalable automation.
🎯 What You’ll Learn:
🧱 What Is Page Object Model (POM)?
→ A design pattern that organizes your test code by creating classes for each page
→ Encapsulates selectors and actions into reusable methods
→ Improves readability, maintainability, and scalability
🛠️ Creating a Page Class in Playwright
→ Example:
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly usernameInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
constructor(page: Page) {
this.page = page;
this.usernameInput = page.locator('#username');
this.passwordInput = page.locator('#password');
this.loginButton = page.locator('#login');
}
async goto() {
await this.page.goto('https://example.com/login');
}
async login(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
}
🔄 Using Page Objects in Tests
→ Example usage in a test file:
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('omar', 'securePassword');
🧠 Best Practices
Keep page classes focused—one per page or component
Use descriptive method names like submitForm() or navigateToDashboard()
Centralize locators to simplify maintenance
Avoid hardcoding URLs—use config or environment variables
🧪 Real-World Use Cases
LoginPage, DashboardPage, CheckoutPage, SettingsPage
Reusable flows like login, search, form submission
Shared components like modals, headers, or sidebars
#Playwright #PageObjectModel #POM #AutomationFramework #TypeScriptTesting #QAEngineer #WebAutomation #SDET #TypeScriptEssentials #ReusableCode