1. Introduction
Modern web applications require reliable and maintainable automation testing. As applications grow, QA Automation Engineers need a structured approach to writing, organizing, and maintaining automated test scripts.
Writing all browser interactions directly inside test files may work for small projects. However, when an application contains multiple pages, forms, and business workflows, maintaining automation scripts becomes difficult.
This is where the Page Object Model (POM) design pattern becomes useful.
A Playwright Page Object Model framework separates application page interactions from test scenarios. Each application page is represented by a TypeScript class containing its locators and reusable methods.
For example, an e-commerce application may contain login, home, product, cart, and checkout pages. Instead of repeating the same locators and actions in multiple test scripts, we create separate page classes and reuse them across tests.
Playwright supports TypeScript, browser automation, fixtures, assertions, and parallel execution, making it suitable for developing a professional automation framework.
In this tutorial, we will learn how to build a Playwright Page Object Model framework from scratch. We will implement page classes, reusable methods, fixtures, environment configuration, login automation, reporting, cross-browser execution, and CI/CD integration.
2. What Is a Playwright Page Object Model Framework?
A Playwright Page Object Model framework is a test automation architecture that uses the Page Object Model design pattern to organize browser interactions into reusable classes.
Each application page has a corresponding page class.
For example:
| Application Page | Page Object Class |
| Login page | LoginPage.ts |
| Home page | HomePage.ts |
| Registration page | RegistrationPage.ts |
| Product page | ProductPage.ts |
| Cart page | CartPage.ts |
| Checkout page | CheckoutPage.ts |
Each page class contains two important components:
- Locators: Identify elements on the application page.
- Methods: Perform actions using those locators.
Playwright POM Framework Architecture
A typical framework follows this execution flow:
|
v
|
v
Page Object Classes
|
v
Reusable Methods
|
v
Playwright Page
|
v
|
v
Assertions and Reports
How does the framework work?
Suppose a tester wants to validate successful login.
The test script creates a LoginPage object, navigates to the login page, enters credentials, clicks the login button, and verifies the dashboard.
The test script does not need to know the implementation details of every locator.
The LoginPage class handles those details.
This separation improves readability and reduces duplicate code.
3. Benefits of Playwright Page Object Model Framework
Using POM provides several advantages for software quality assurance teams.
3.1 Code reusability
The same page methods can be reused across multiple test cases.
For example, the login() method can be used by profile tests, product tests, and checkout tests.
3.2 Maintainability
If a login button locator changes, the tester updates it in LoginPage.ts rather than modifying multiple test files.
3.3 Improved readability
Test scripts become shorter because application interactions are handled inside page classes.
3.4 Reduced code duplication
Common locators and actions are maintained in one place.
3.5 Scalability
New application pages can be introduced by creating additional page classes.
3.6 Easier debugging
Locating problems becomes easier because page interactions are organized by application functionality.
POM also has limitations. Creating too many unnecessary page classes, duplicating business logic, or building very large page objects can make a framework complicated. Good framework design keeps page classes focused and reusable.
4. Prerequisites and Playwright TypeScript Project Setup
Before creating the Playwright Page Object Model framework, install these tools:
| Technology | Purpose |
| Node.js | JavaScript runtime |
| npm | Package management |
| TypeScript | Programming language |
| Playwright | Browser automation |
| VS Code | Code editor |
| Git | Version control |
| Jenkins / GitHub Actions | CI/CD |
Basic knowledge of TypeScript, JavaScript, HTML, CSS, and software testing is recommended.
Step 1: Create a project
Open your terminal:
mkdir playwright-pom-framework
cd playwright-pom-framework
Initialize the project:
npm init -y
Step 2: Install Playwright
npm install -D @playwright/test
Install TypeScript:
npm install -D typescript @types/node
Install browser binaries:
Install dotenv:
npm install dotenv
Step 3: Create tsconfig.json
{
“compilerOptions”: {
“target”: “ES2020”,
“module”: “commonjs”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“types”: [“node”, “@playwright/test”],
“outDir”: “dist”
},
“include”: [
“pages”,
“tests”,
“fixtures”,
“utils”,
“config”
]
}
The strict TypeScript configuration helps identify incorrect types and programming mistakes during development.
5. Recommended Playwright POM Framework Folder Structure
A well-organized project structure is important for maintaining automation scripts.
Create the following folder structure:
playwright-pom-framework/
│
├── config/
│ └── environment.ts
│
├── pages/
│ ├── LoginPage.ts
│ ├── HomePage.ts
│ └── ProductPage.ts
│
├── tests/
│ ├── login.spec.ts
│ └── product.spec.ts
│
├── fixtures/
│ └── testFixture.ts
│
├── test-data/
│ └── users.json
│
├── utils/
│ └── logger.ts
│
├── test-results/
├── playwright-report/
│
├── .env
├── .gitignore
├── playwright.config.ts
├── tsconfig.json
└── package.json
Folder explanations
| Folder | Responsibility |
| pages | Contains Page Object Model classes |
| tests | Contains automated test scenarios |
| fixtures | Provides reusable test dependencies |
| test-data | Stores external test data |
| utils | Contains reusable helper functions |
| config | Stores environment configuration |
| test-results | Stores screenshots and execution artifacts |
| playwright-report | Contains HTML reports |
This structure separates page interactions, test logic, and supporting framework components.
6. Creating Page Classes in Playwright TypeScript
Page classes are the foundation of the POM architecture.
Each class should represent a meaningful application page or reusable component.
Let’s create a login page.
Step 1: Create LoginPage.ts
Inside the pages folder, create LoginPage.ts.
import { Page, Locator } from ‘@playwright/test’;
export class LoginPage {
readonly page: Page;
readonly username: Locator;
readonly password: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.username = page.getByLabel(‘Username’);
this.password = page.getByLabel(‘Password’);
this.loginButton = page.getByRole(‘button’, {
name: ‘Login’
});
this.errorMessage = page.locator(‘.error-message’);
}
async navigate() {
await this.page.goto(‘/login’);
}
async login(user: string, pass: string) {
await this.username.fill(user);
await this.password.fill(pass);
await this.loginButton.click();
}
}
Explanation
The constructor receives a Playwright Page object.
The locators identify the username, password, login button, and error message.
The navigate() method opens the login page.
The login() method enters the credentials and clicks the login button.
Using accessible locators such as getByLabel() and getByRole() is generally preferable when the application supports them.
Step 2: Create HomePage.ts
import { Page, Locator } from ‘@playwright/test’;
export class HomePage {
readonly page: Page;
readonly heading: Locator;
readonly profileButton: Locator;
readonly logoutButton: Locator;
constructor(page: Page) {
this.page = page;
this.heading = page.getByRole(‘heading’, {
name: ‘Dashboard’
});
this.profileButton = page.locator(‘#profile’);
this.logoutButton = page.getByRole(‘button’, {
name: ‘Logout’
});
}
async openProfile() {
await this.profileButton.click();
}
async logout() {
await this.logoutButton.click();
}
}
This class contains reusable actions for the home or dashboard page.
If multiple test cases need to open the profile or log out, they can reuse these methods.
7. Implementing the Playwright Page Object Model Framework
Now let’s connect the page classes with test scripts.
Create tests/login.spec.ts:
import { test, expect } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { HomePage } from ‘../pages/HomePage’;
test.describe(‘Login Page Tests‘, () => {
test(‘Verify successful login’, async ({ page }) => {
const loginPage = new LoginPage(page);
const homePage = new HomePage(page);
await loginPage.navigate();
await loginPage.login(
‘testuser@example.com’,
‘Password123’
);
await expect(
homePage.heading
).toBeVisible();
});
});
Understanding the test
- Import the Playwright test runner.
- Import LoginPage and HomePage classes.
- Create page object instances.
- Navigate to the login page.
- Enter login credentials.
- Verify that the dashboard heading appears.
Notice that the test file does not contain the username, password, or login button locators.
All those implementation details are maintained inside LoginPage.ts.
This is the main advantage of the Playwright Page Object Model framework.
The example assumes the application has the specified labels, routes, credentials, and dashboard heading. Replace them with your application’s actual details.
8. Real-World Login Automation Using Page Object Model
Let’s extend the example to support both successful and unsuccessful login scenarios.
Step 1: Create users.json
Inside test-data, create users.json:
[
{
“username”: “validuser@example.com”,
“password”: “Password123”,
“scenario”: “valid”
},
{
“username”: “invaliduser@example.com”,
“password”: “Wrong123”,
“scenario”: “invalid”
}
]
These are sample test values. Use valid application test accounts and secure storage for sensitive credentials.
Step 2: Implement data-driven login testing
Create tests/login.spec.ts:
import { test, expect } from ‘@playwright/test’;
import users from ‘../test-data/users.json’;
import { LoginPage } from ‘../pages/LoginPage’;
import { HomePage } from ‘../pages/HomePage’;
test.describe(‘Data Driven Login Tests’, () => {
for (const user of users) {
test(`Login scenario: ${user.scenario}`, async ({ page }) => {
const loginPage = new LoginPage(page);
const homePage = new HomePage(page);
await loginPage.navigate();
await loginPage.login(
user.username,
user.password
);
if (user.scenario === ‘valid’) {
await expect(
homePage.heading
).toBeVisible();
} else {
await expect(
loginPage.errorMessage
).toBeVisible();
}
});
}
});
Make sure resolveJsonModule is enabled in tsconfig.json.
This example combines POM and data-driven testing. The page class handles interactions, while the test data file provides different login combinations.
9. Implementing Reusable Fixtures in the POM Framework
Fixtures help create reusable dependencies and reduce repeated object initialization.
Instead of creating page objects manually inside every test, we can register them as custom fixtures.
Create fixtures/testFixture.ts:
import { test as base } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { HomePage } from ‘../pages/HomePage’;
type MyFixtures = {
loginPage: LoginPage;
homePage: HomePage;
};
export const test = base.extend<MyFixtures>({
loginPage: async ({ page }, use) => {
const login = new LoginPage(page);
await use(login);
},
homePage: async ({ page }, use) => {
const home = new HomePage(page);
await use(home);
}
});
export { expect } from ‘@playwright/test’;
Now test scripts can use the page objects directly.
import { test, expect } from ‘../fixtures/testFixture’;
test(‘Verify dashboard’, async ({
loginPage,
homePage
}) => {
await loginPage.navigate();
await loginPage.login(
‘testuser@example.com’,
‘Password123’
);
await expect(
homePage.heading
).toBeVisible();
});
The custom fixtures create page objects using the current test’s Playwright Page instance.
This makes the framework cleaner and easier to extend.
10. Environment Configuration and Cross-Browser Testing
A professional Playwright POM framework should support multiple testing environments.
Create .env:
BASE_URL=https://example.com
USERNAME=testuser@example.com
PASSWORD=Password123
Create config/environment.ts:
import dotenv from ‘dotenv’;
dotenv.config();
export const environment = {
baseURL: process.env.BASE_URL || ‘https://example.com’,
username: process.env.USERNAME || ”,
password: process.env.PASSWORD || ”
};
Create playwright.config.ts:
import { defineConfig, devices } from ‘@playwright/test’;
import { environment } from ‘./config/environment’;
export default defineConfig({
testDir: ‘./tests’,
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
],
use: {
baseURL: environment.baseURL,
headless: true,
screenshot: ‘only-on-failure’,
trace: ‘retain-on-failure’
},
projects: [
{
name: ‘chromium’,
use: { …devices[‘Desktop Chrome’] }
},
{
name: ‘firefox’,
use: { …devices[‘Desktop Firefox’] }
},
{
name: ‘webkit’,
use: { …devices[‘Desktop Safari’] }
}
]
});
Cross-browser execution
Run Chromium tests:
npx playwright test –project=chromium
Run Firefox tests:
npx playwright test –project=firefox
Run WebKit tests:
npx playwright test –project=webkit
Playwright can execute the same test suite across multiple browser engines using projects.
11. Reporting and Debugging in Playwright POM Framework
Reporting helps QA engineers analyze test execution and investigate failures.
Playwright provides built-in HTML reporting.
Configure the HTML reporter:
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
]
Run automation tests:
npx playwright test
Open the HTML report:
npx playwright show-report
Screenshot capture
You can capture screenshots manually:
await page.screenshot({
path: ‘test-results/homepage.png’,
fullPage: true
});
Create the destination directory before saving a screenshot to a custom location.
Debugging
npx playwright test –debug
Open an execution trace:
npx playwright show-trace trace.zip
Trace Viewer helps investigate browser actions, DOM snapshots, network requests, and screenshots.
For enterprise frameworks, configure failure screenshots and trace retention so debugging information is available after CI execution.
12. CI/CD Integration Using GitHub Actions
A Playwright Page Object Model framework can be integrated with GitHub Actions to execute automation tests whenever code changes are pushed.
Create .github/workflows/playwright.yml:
name: Playwright POM Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
– name: Checkout code
uses: actions/checkout@v6
– name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
– name: Install dependencies
run: npm ci
– name: Install browsers
run: npx playwright install –with-deps
– name: TypeScript validation
run: npx tsc –noEmit
– name: Execute tests
run: npx playwright test
– name: Upload report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v5
with:
name: playwright-report
path: playwright-report/
This workflow installs dependencies, installs browsers, validates TypeScript, executes tests, and uploads the HTML report.
The same framework can be integrated with Jenkins using a pipeline that runs npm ci, installs browsers, executes npx tsc –noEmit, and runs npx playwright test.
13. Execution Commands and Expected Results
Add the following scripts to package.json:
{
“scripts”: {
“test”: “playwright test”,
“test:headed”: “playwright test –headed,
“test:ui”: “playwright test –ui,
“test:chrome”: “playwright test –project=chromium,
“test:firefox”: “playwright test –project=firefox,
“test:webkit”: “playwright test –project=webkit,
“report”: “playwright show-report”,
“typecheck”: “tsc –noEmit”
}
}
Validate TypeScript:
npm run typecheck
Execute all tests:
npm test
Execute in headed mode:
npm run test:headed
Open the HTML report:
npm run report
Expected output:
Running 2 tests
✓ Verify successful login
✓ Login scenario: invalid
2 passed
To open the HTML report:
npx playwright show-report
Actual results depend on the application, test data, and configured browser projects.
14. Best Practices and Common Mistakes
Best practices
1. Keep page classes focused
Each page class should represent a meaningful page or reusable component.
2. Use meaningful method names
Prefer login(), logout(), openCart(), and searchProduct() instead of unclear names.
3. Prefer accessible locators
Use getByRole(), getByLabel(), and getByText() when appropriate.
4. Separate test logic from page interactions
Page classes should contain reusable application interactions. Test files should contain scenarios and validations.
5. Use fixtures
Fixtures help provide page objects and common dependencies.
6. Avoid unnecessary fixed waits
Do not rely on page.waitForTimeout() for normal synchronization. Prefer Playwright’s auto-waiting and web-first assertions.
7. Manage credentials securely
Use environment variables and CI/CD secrets rather than committing passwords.
Common mistakes
| Mistake | Recommended solution |
| Writing all locators inside tests | Move locators into page classes |
| Creating very large page classes | Split reusable components |
| Duplicating methods | Reuse existing page methods |
| Using unclear method names | Follow naming conventions |
| Hardcoding credentials | Use secure configuration |
| Adding assertions everywhere in page objects | Keep scenario validation in tests where practical |
| Creating unnecessary inheritance | Prefer simple composition |
| Ignoring test isolation | Use independent test data |
A good POM framework should remain simple, reusable, and easy to understand.
15. Playwright Page Object Model Interview Questions and FAQs
1. What is Playwright Page Object Model?
Page Object Model is a design pattern that represents application pages as classes containing locators and reusable methods.
2. How do I get started with Playwright Page Object Model framework?
Install Playwright and TypeScript, create a project structure, implement page classes, write test scripts, and configure reporting and browser execution.
3. What are the benefits of Playwright Page Object Model framework?
The main benefits are code reusability, maintainability, improved readability, reduced duplication, and easier debugging.
4. Is Page Object Model mandatory in Playwright?
No. Playwright does not require POM. However, it is useful for applications with multiple pages and repeated application interactions.
5. What is the difference between Page and Page Object?
Page is a Playwright browser-page API object used to interact with a browser tab.
A Page Object is a custom TypeScript class that organizes locators and actions for an application page.
6. Can we use fixtures with Page Object Model?
Yes. Custom fixtures can create and provide page object instances to test scripts.
7. How do we manage test data in a POM framework?
Test data can be stored in JSON files, TypeScript arrays, or external data sources and passed to page methods from test scripts.
8. Can we perform API testing in a POM framework?
Yes. Playwright supports API testing through its request fixture and API request capabilities. API helpers can be organized separately from UI page objects.
9. Can Playwright POM tests run in parallel?
Yes. Playwright supports parallel execution using workers. Tests should be independent and avoid shared mutable test data.
10. How is Playwright POM different from Selenium POM?
Both use the same general Page Object Model design pattern. Playwright provides built-in auto-waiting, browser contexts, fixtures, and test execution capabilities, while Selenium projects commonly use additional test runners and framework components.
