Creating a Basic Page Object Class
What you'll learn: How to write your first Page Object class by grouping locators and actions for a single page or component into one reusable structure.
The Core Idea
A Page Object is simply a class (or object) that encapsulates everything related to interacting with a specific page or component. Instead of scattering page.getByRole() and page.click() calls throughout your tests, you collect them in one place with meaningful method names.
Think of it like creating a remote control for your page. Instead of manually pressing buttons on the TV, you have labeled buttons like "changeChannel" and "adjustVolume" that hide the complexity.
Basic Structure
Here's a simple Page Object for a login page:
class LoginPage {
constructor(page) {
this.page = page;
// Define locators
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.submitButton = page.getByRole('button', { name: 'Sign In' });
this.errorMessage = page.getByRole('alert');
}
async login(email, password) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.submitButton.click();
}
async getErrorText() {
return await this.errorMessage.textContent();
}
}
Now your test becomes readable:
test('login with invalid credentials shows error', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.login('bad@example.com', 'wrong');
await expect(loginPage.errorMessage).toBeVisible();
});
The locators live in the constructor, and actions become methods. When the page changes, you update one class, not dozens of tests.
Key Takeaway: A Page Object class groups all locators and actions for a page into a single reusable class, making tests more maintainable and readable by hiding implementation details behind meaningful method names.