1. Introduction to Page Object Model in Playwright TypeScript
Modern web applications require reliable automation testing to validate functionality across different browsers and environments. As applications grow, maintaining automated test scripts becomes challenging when locators, browser actions, and assertions are written directly inside test cases.
To solve this problem, automation engineers use design patterns such as Page Object Model (POM).
Playwright is an open-source browser automation framework developed by Microsoft. It supports Chromium, Firefox, and WebKit and provides powerful features for end-to-end testing.
The playwright typescript page object model combines Playwright automation capabilities with TypeScript classes to create reusable and maintainable automation frameworks.
Instead of writing the same login locators in multiple test files, you can create a separate LoginPage class containing locators and reusable methods.
For example, an e-commerce application may have different pages:
- Login page
- Home page
- Product page
- Shopping cart page
- Checkout page
- Order confirmation page
Each page can have its own TypeScript class. Test scripts can interact with these classes without repeatedly defining browser locators.
In this tutorial, we will build a practical Playwright TypeScript POM framework from scratch using page classes, reusable methods, fixtures, test data, assertions, and reporting.
2. What Is Page Object Model and Why Use It?
Page Object Model is a design pattern used in automation testing to separate application page interactions from test scripts.
Each application page is represented by a separate class.
The class contains:
- Page locators.
- Page navigation methods.
- Reusable actions.
- Common interactions.
For example, a LoginPage class can contain username, password, and login button locators along with a reusable login method.
Traditional Approach vs Page Object Model
| Traditional Test Scripts | Page Object Model |
| Locators inside test files | Locators inside page classes |
| Duplicate code | Reusable methods |
| Difficult maintenance | Easier maintenance |
| Test logic and page actions mixed | Responsibilities separated |
| Less suitable for large projects | Suitable for scalable projects |
Benefits of Playwright TypeScript POM
- Improves code reusability.
- Reduces duplicate automated test scripts.
- Makes maintenance easier.
- Separates test logic from browser interactions.
- Supports TypeScript type checking.
- Makes large automation projects easier to organize.
- Helps multiple QA engineers collaborate.
For QA engineering teams, POM provides a structured approach to developing maintainable browser automation frameworks.
3. Prerequisites and Project Setup
Before implementing the Page Object Model, install the required software.
| Requirement | Purpose |
| Node.js | Executes JavaScript and TypeScript tooling |
| npm | Manages project dependencies |
| Visual Studio Code | Code editor |
| Playwright | Browser automation |
| TypeScript | Programming language |
| Basic HTML and CSS | Understanding web elements |
Step 1: Install Node.js
Download Node.js from:
Verify the installation:
node -v
npm -v
Step 2: Create a Project
Open your terminal:
mkdir playwright-typescript-pom
cd playwright-typescript-pom
Initialize the project:
npm init -y
Step 3: Install Playwright and TypeScript
npm install -D @playwright/test typescript
Install browser binaries:
Create the TypeScript configuration:
npx tsc –init
You can also use the official Playwright installer to generate a starter project:
npm init playwright@latest
Select TypeScript when prompted.
4. Recommended Playwright TypeScript POM Folder Structure
A well-organized folder structure is important when building a reusable Page Object Model framework.
Create the following structure:
playwright-typescript-pom/
│
├── tests/
│ ├── login.spec.ts
│ └── dashboard.spec.ts
│
├── pages/
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│ └── HomePage.ts
│
├── fixtures/
│ └── test-fixtures.ts
│
├── test-data/
│ └── users.json
│
├── utils/
│ └── TestUtils.ts
│
├── playwright.config.ts
├── tsconfig.json
├── package.json
│
├── playwright-report/
├── test-results/
│
└── .github/
└── workflows/
└── playwright.yml
Explanation of Important Folders
tests: Contains automated test cases.
pages: Stores page classes, locators, and reusable methods.
fixtures: Manages reusable test setup and page objects.
test-data: Stores usernames, passwords, and other test inputs.
utils: Contains common helper functions.
playwright.config.ts: Manages browser configuration, execution settings, and reporting.
This structure makes the project easier to maintain as the application grows.
5. Create Page Classes and Reusable Methods
In the Playwright TypeScript Page Object Model, every important application page can be represented using a TypeScript class.
A page class generally contains:
- A Page object.
- Locator properties.
- A constructor.
- Navigation methods.
- Reusable interaction methods.
Let’s create a login page.
6. Implement Login Page Using TypeScript
Consider an application with a login form containing username, password, and login button fields.
Create pages/LoginPage.ts.
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.getByLabel(‘Username’);
this.password = page.getByLabel(‘Password’);
this.loginButton = page.getByRole(‘button’, {
name: ‘Login’
});
}
async navigate() {
await this.page.goto(‘/login’);
}
async enterUsername(username: string) {
await this.username.fill(username);
}
async enterPassword(password: string) {
await this.password.fill(password);
}
async clickLogin() {
await this.loginButton.click();
}
async login(username: string, password: string) {
await this.enterUsername(username);
await this.enterPassword(password);
await this.clickLogin();
}
}
Explanation
Page: Represents the browser page.
Locator: Represents an element on the application page.
Constructor: Initializes the page object and its locators.
navigate(): Opens the login page.
enterUsername(): Enters the username.
enterPassword(): Enters the password.
clickLogin(): Clicks the login button.
login(): Combines the login operations into one reusable method.
This approach allows multiple test cases to reuse the same login functionality.
The example assumes the application provides accessible Username and Password labels and a button named Login.
Create DashboardPage.ts
After successful login, the application redirects users to a dashboard.
Create pages/DashboardPage.ts.
import { Page, Locator } from ‘@playwright/test’;
export class DashboardPage {
readonly page: Page;
readonly heading: Locator;
readonly logoutButton: Locator;
constructor(page: Page) {
this.page = page;
this.heading = page.getByRole(‘heading’, {
name: ‘Dashboard’
});
this.logoutButton = page.getByRole(‘button’, {
name: ‘Logout’
});
}
async logout() {
await this.logoutButton.click();
}
}
Now the framework has separate classes for login and dashboard functionality.
7. Write Test Scripts Using Page Objects
Once the page classes are ready, create automated test scripts.
Create tests/login.spec.ts.
import { test, expect } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { DashboardPage } from ‘../pages/DashboardPage’;
test(‘Verify successful login’, async ({ page }) => {
const loginPage = new LoginPage(page);
const dashboardPage = new DashboardPage(page);
await loginPage.navigate();
await loginPage.login(
‘testuser’,
‘Password123’
);
await expect(
dashboardPage.heading
).toBeVisible();
});
Test Execution Flow
- Playwright creates a browser page.
- The LoginPage object initializes its locators.
- The test navigates to the login page.
- Username and password are entered.
- The login button is clicked.
- The application redirects to the dashboard.
- The test verifies that the dashboard heading is visible.
The example uses sample credentials and assumes the application has a matching login workflow.
Execute the Test
npx playwright test
Run only the login test:
npx playwright test tests/login.spec.ts
Run with a visible browser:
npx playwright test –headed
This demonstrates how page objects keep test scripts clean and readable.
8. Use Fixtures and Manage Reusable Components
Fixtures help manage common test dependencies such as browser pages and page objects.
Instead of creating page objects manually in every test, you can create custom fixtures.
Create fixtures/test-fixtures.ts.
import {
test as base,
expect
} from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { DashboardPage } from ‘../pages/DashboardPage’;
type MyFixtures = {
loginPage: LoginPage;
dashboardPage: DashboardPage;
};
export const test = base.extend<MyFixtures>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
dashboardPage: async ({ page }, use) => {
await use(new DashboardPage(page));
}
});
export { expect };
Use Fixtures in Test Scripts
Now update tests/login.spec.ts.
import {
test,
expect
} from ‘../fixtures/test-fixtures’;
test(‘Verify successful login’, async ({
loginPage,
dashboardPage
}) => {
await loginPage.navigate();
await loginPage.login(
‘testuser’,
‘Password123’
);
await expect(
dashboardPage.heading
).toBeVisible();
});
Playwright automatically creates the required page and passes the custom page objects into the test.
Fixtures improve consistency and reduce repeated initialization code.
9. Handle Assertions, Test Data, and Multiple Pages
A professional Playwright TypeScript POM framework should separate test data from test logic.
Manage Test Data Using JSON
Create test-data/users.json.
{
“validUser”: {
“username”: “testuser”,
“password”: “Password123”
}
}
Import the data into your test:
import users from ‘../test-data/users.json’;
Use it during login:
await loginPage.login(
users.validUser.username,
users.validUser.password
);
Enable JSON imports in tsconfig.json:
{
“compilerOptions”: {
“resolveJsonModule”: true,
“esModuleInterop”: true,
“strict”: true,
“skipLibCheck”: true
}
}
Use environment variables or secret management for real credentials instead of committing passwords to Git.
Handle Assertions
Playwright provides web-first assertions.
await expect(
dashboardPage.heading
).toBeVisible();
await expect(page).toHaveURL(/dashboard/);
These assertions automatically retry until the expected condition is satisfied or the timeout expires.
Handle Multiple Pages
You can create another browser tab using:
const newPage = await context.newPage();
await newPage.goto(‘https://example.com’);
For a multi-page workflow, you can initialize the appropriate page object using the new page:
const homePage = new HomePage(newPage);
This approach is useful when testing applications that open new tabs or interact with multiple pages.
10. Integrate POM with Reporting and CI/CD
Reporting and CI/CD integration are important for professional automation frameworks.
Configure HTML Reporting
Add the following settings to playwright.config.ts:
import { defineConfig } from ‘@playwright/test’;
export default defineConfig({
testDir: ‘./tests’,
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
],
use: {
baseURL: ‘https://example.com’,
screenshot: ‘only-on-failure’,
trace: ‘retain-on-failure’
}
});
npx playwright test
Open the report:
npx playwright show-report
Debug Failed Tests
Use UI Mode:
npx playwright test –ui
Use debug mode:
npx playwright test –debug
These commands help investigate locator failures, navigation problems, and unexpected browser behavior.
GitHub Actions Integration
Create .github/workflows/playwright.yml.
name: Playwright POM Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v6
– uses: actions/setup-node@v6
with:
node-version: lts/*
– name: Install Dependencies
run: npm ci
– name: Install Browsers
run: npx playwright install –with-deps
– name: Run Tests
run: npx playwright test
– uses: actions/upload-artifact@v5
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
retention-days: 30
This pipeline installs dependencies, downloads browser binaries, executes the automation suite, and stores the HTML report as an artifact.
11. Best Practices for Playwright TypeScript Page Object Model
Follow these practices when building a maintainable POM framework.
1. Create separate page classes: Maintain one class for each important application page.
2. Use reusable methods: Avoid repeating login, navigation, and form-filling operations.
3. Prefer reliable locators: Use getByRole(), getByLabel(), and getByTestId() where appropriate.
4. Keep assertions in tests: Page objects should generally manage interactions, while test files should validate expected outcomes.
5. Use TypeScript types: Define proper types for methods and test data.
6. Use fixtures: Manage reusable page objects and common setup logic.
7. Maintain separate test data: Keep input data outside test scripts.
8. Avoid hard-coded waits: Use Playwright auto-waiting and web-first assertions.
9. Keep tests independent: Avoid dependencies between test cases.
10. Integrate reporting: Use HTML reports, screenshots, and traces to investigate failures.
12. Common POM Mistakes and Troubleshooting
| Problem | Possible Reason | Solution |
| Locator not found | Incorrect locator or page structure | Inspect the application and update the locator |
| Page object import error | Incorrect file path | Verify import statements |
| Fixture not recognized | Incorrect fixture export | Check custom fixture definitions |
| Test timeout | Application is slow or action is blocked | Investigate the failing operation |
| JSON import error | Incorrect TypeScript settings | Enable resolveJsonModule |
| Duplicate test execution | Multiple browser projects configured | Check project configuration |
| Flaky tests | Shared test data or unstable application state | Isolate tests and data |
13. Frequently Asked Questions
Q1. What are the benefits of Playwright TypeScript Page Object Model?
The main benefits include reusable methods, better code organization, maintainability, reduced duplication, and easier collaboration between automation engineers.
Q2. Is Playwright TypeScript Page Object Model suitable for beginners?
Yes. Beginners can start with simple TypeScript classes and gradually learn locators, constructors, reusable methods, fixtures, and assertions.
Q3. How do I get started with Playwright TypeScript Page Object Model?
Install Node.js and Playwright, create a project, organize page classes inside a pages folder, implement locators and reusable methods, and create test scripts that use those classes.
Q4. What is the difference between Selenium POM and Playwright POM?
Both use the Page Object Model design pattern. Selenium commonly uses WebDriver APIs, while Playwright uses its Page and Locator APIs. Playwright also provides built-in fixtures and web-first assertions.
Q5. Should assertions be written inside page classes?
Generally, assertions belong in test scripts because they validate expected outcomes. Page objects should primarily manage page interactions and reusable application operations. Some specialized component abstractions may have their own validation methods when appropriate.
Q6. Can we use fixtures with Page Object Model?
Yes. Custom Playwright fixtures can initialize page objects and provide them directly to test scripts.
