Simple Example of POM in Playwright

Let’s create a basic login page object.

Step 1: Create LoginPage.ts

import { Page, Locator } from '@playwright/test';

export class LoginPage {
    readonly page: Page;
    readonly username: Locator;
    readonly password: Locator;
    readonly loginButton: Locator;

    constructor(page: Page) {
        this.page = page;

        this.username = page.locator('#username');
        this.password = page.locator('#password');
        this.loginButton = page.locator('#login');
    }

    async login(username: string, password: string) {
        await this.username.fill(username);
        await this.password.fill(password);
        await this.loginButton.click();
    }
}

Don’t worry if this code looks new.

The important idea is:

Locators + page actions = Page Object


Step 2: Use the Page Object in Your Test

Now create a test:

import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';

test('User should be able to login', async ({ page }) => {

    const loginPage = new LoginPage(page);

    await page.goto('https://example.com/login');

    await loginPage.login('testuser', 'password123');

    await expect(page).toHaveURL(/dashboard/);
});

Notice how simple the test is.

The test doesn’t need to know:

All those details are inside LoginPage.


Pages: 1 2 3 4 5 6 7

Leave a Reply

Your email address will not be published. Required fields are marked *