1. Introduction
Building automated test scripts is only the first step in successful test automation. When a project grows, maintaining hundreds of independent test scripts becomes difficult. Testers may face duplicate code, inconsistent test data, difficult debugging, and unreliable execution.
This is why designing a proper automation framework is important.
Playwright provides powerful browser automation capabilities, but a well-designed framework adds structure, reusability, maintainability, and scalability to the automation process.
In this tutorial, we will learn Playwright framework design from scratch using TypeScript. We will build a practical framework with the Page Object Model (POM), reusable fixtures, environment configuration, test data management, API testing, cross-browser execution, reporting, and CI/CD integration.
By the end, you will understand how QA Automation Engineers and SDETs can design a professional Playwright automation framework for real-world projects.
2. What Is a Playwright Automation Framework?
A Playwright automation framework is a structured collection of reusable components, automated test scripts, configuration files, utilities, and reporting mechanisms used to test web applications.
Playwright Test provides built-in capabilities such as:
- Browser automation using Chromium, Firefox, and WebKit.
- Automatic waiting and web-first assertions.
- Test execution and parallelization.
- Browser and context isolation.
- Fixtures and hooks.
- Screenshots, videos, and traces.
- HTML reporting.
- API testing.
A framework organizes these capabilities into a maintainable architecture.
For example, consider an e-commerce application with the following features:
- User login
- Product search
- Add to cart
- Checkout
- Payment validation
- Order confirmation
Instead of writing all automation logic inside individual test files, we separate the application interactions, test data, configuration, and validation logic.
Playwright Framework Architecture
A typical framework follows this execution flow:
|
v
Test Specifications
|
v
|
v
|
v
|
v
|
v
Assertions and Validation
|
v
Reports and Logs
This architecture makes the automation framework easier to maintain and extend.
3. Prerequisites and Playwright TypeScript Installation
Before starting Playwright framework design from scratch, install the following tools:
| Tool | Purpose |
| Node.js | JavaScript runtime |
| npm | Package management |
| TypeScript | Programming language |
| Playwright | Browser automation |
| Visual Studio Code | Code editor |
| Git | Version control |
| Jenkins or GitHub Actions | CI/CD execution |
You should have basic knowledge of JavaScript, TypeScript, HTML, CSS, and software testing concepts.
Step 1: Create a project
Create a new directory:
mkdir playwright-framework
cd playwright-framework
Initialize the Node.js project:
npm init -y
Step 2: Install Playwright
Install Playwright Test:
npm install -D @playwright/test
Install TypeScript and Node.js type definitions:
npm install -D typescript @types/node
Install browser binaries:
Step 3: Install dotenv
We will use dotenv to manage environment variables.
npm install dotenv
Step 4: Create TypeScript configuration
Create tsconfig.json:
{
“compilerOptions”: {
“target”: “ES2020”,
“module”: “commonjs”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“types”: [“node”, “@playwright/test”],
“outDir”: “dist”
},
“include”: [“tests”, “pages”, “fixtures”, “utils”]
}
Playwright supports TypeScript directly. However, running the TypeScript compiler separately helps identify type errors before executing tests.
4. Step-by-Step Playwright Framework Creation From Scratch
Now let’s create a practical Playwright TypeScript framework.
We will use an e-commerce application as our example and automate the login and product selection workflows.
Step 1: Create the project folder structure
Create the following structure:
playwright-framework/
│
├── config/
│ └── environment.ts
│
├── pages/
│ ├── LoginPage.ts
│ └── HomePage.ts
│
├── tests/
│ ├── login.spec.ts
│ └── product.spec.ts
│
├── fixtures/
│ └── testFixture.ts
│
├── test-data/
│ └── users.json
│
├── utils/
│ └── logger.ts
│
├── .github/
│ └── workflows/
│ └── playwright.yml
│
├── .env
├── .gitignore
├── playwright.config.ts
├── tsconfig.json
└── package.json
Explanation of Each Folder
config: Stores environment-specific configuration, such as application URLs and execution settings.
pages: Contains Page Object Model classes. Each class represents a page or a meaningful application component.
tests: Contains test specification files with test scenarios and assertions.
fixtures: Provides reusable test setup, teardown, and custom test dependencies.
test-data: Stores external test data such as usernames, passwords, product information, and test scenarios.
utils: Contains reusable helper functions such as logging and data handling.
.github/workflows: Stores GitHub Actions pipeline configuration.
This separation prevents duplicate code and improves framework maintainability.
5. Playwright Configuration, Environment Variables, and Browser Setup
The playwright.config.ts file is the central configuration file.
It controls browser selection, base URL, timeouts, retries, parallel execution, screenshots, traces, and reporting.
Step 1: Configure environment variables
Create a .env file:
BASE_URL=https://example.com
TEST_USERNAME=testuser@example.com
TEST_PASSWORD=TestPassword123
Use your own application URL and valid test credentials.
Create config/environment.ts:
import dotenv from ‘dotenv’;
dotenv.config();
export const environment = {
baseURL: process.env.BASE_URL || ‘https://example.com’,
username: process.env.TEST_USERNAME || ”,
password: process.env.TEST_PASSWORD || ”
};
Avoid committing real credentials or sensitive environment files to Git.
Step 2: Create Playwright configuration
Create playwright.config.ts:
import { defineConfig, devices } from ‘@playwright/test’;
import { environment } from ‘./config/environment’;
export default defineConfig({
testDir: ‘./tests’,
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
],
use: {
baseURL: environment.baseURL,
headless: true,
actionTimeout: 10000,
navigationTimeout: 30000,
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’]
}
}
]
});
Important configuration properties
- testDir: Defines where test files are stored.
- fullyParallel: Enables parallel execution of independent tests.
- retries: Repeats failed tests according to the configured limit.
- workers: Controls parallel worker processes.
- reporter: Defines the reporting format.
- baseURL: Sets the application’s base URL.
- screenshot: Captures screenshots when tests fail.
- trace: Retains execution traces for debugging.
- projects: Defines different browser configurations.
For CI environments, starting with one worker can improve execution stability. Increase workers after evaluating the available resources.
6. Implementing Page Object Model in Playwright TypeScript
Page Object Model is one of the most important design patterns in automation framework development.
It separates page interactions from test scenarios.
For example, login-related locators and actions belong inside LoginPage.ts, while login validation belongs inside the test specification.
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;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.username = page.locator(‘#username’);
this.password = page.locator(‘#password’);
this.loginButton = page.locator(‘#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 the Playwright Page object.
Locators identify application elements. The login() method performs the login operation.
If the login page changes, we can update the locators in one place instead of modifying multiple test scripts.
Step 2: Create HomePage.ts
import { Page, Locator } from ‘@playwright/test’;
export class HomePage {
readonly page: Page;
readonly heading: Locator;
readonly product: Locator;
readonly cartButton: Locator;
constructor(page: Page) {
this.page = page;
this.heading = page.locator(‘h1’);
this.product = page.locator(‘.product-item’);
this.cartButton = page.locator(‘#cart’);
}
async selectProduct() {
await this.product.first().click();
}
async openCart() {
await this.cartButton.click();
}
}
Step 3: Create login.spec.ts
import { test, expect } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { HomePage } from ‘../pages/HomePage’;
import { environment } from ‘../config/environment’;
test(‘Verify successful user login’, async ({ page }) => {
const loginPage = new LoginPage(page);
const homePage = new HomePage(page);
await loginPage.navigate();
await loginPage.login(
environment.username,
environment.password
);
await expect(homePage.heading).toBeVisible();
});
This test demonstrates how the Page Object Model separates application interactions from validation.
The example selectors and routes must match your actual application.
7. Creating Reusable Utilities, Fixtures, Hooks, and Test Data
A professional Playwright automation framework should avoid repeating the same setup logic in every test.
Fixtures and reusable utilities help achieve this.
Step 1: Create test data
Create test-data/users.json:
{
“validUser”: {
“username”: “testuser@example.com”,
“password”: “TestPassword123”
},
“invalidUser”: {
“username”: “invalid@example.com”,
“password”: “wrongpassword”
}
}
Import this data into your test scripts when required.
For production environments, use secrets rather than storing actual credentials in JSON files.
Step 2: Create reusable 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 files can access page objects directly through fixtures.
Example:
import { test, expect } from ‘../fixtures/testFixture’;
import { environment } from ‘../config/environment’;
test(‘Login using reusable fixture’, async ({
loginPage,
homePage
}) => {
await loginPage.navigate();
await loginPage.login(
environment.username,
environment.password
);
await expect(homePage.heading).toBeVisible();
});
Step 3: Understand hooks
Playwright supports hooks such as:
- beforeEach(): Executes before every test.
- afterEach(): Executes after every test.
- beforeAll(): Executes once before tests in a file.
- afterAll(): Executes once after tests in a file.
Example:
import { test, expect } from ‘@playwright/test’;
test.beforeEach(async ({ page }) => {
await page.goto(‘/’);
});
test(‘Verify homepage title’, async ({ page }) => {
await expect(page).toHaveTitle(/Example/);
});
test.afterEach(async ({ page }, testInfo) => {
console.log(`Completed: ${testInfo.title}`);
});
Use hooks for shared setup and cleanup. Avoid placing unrelated business logic inside global hooks.
Step 4: Create a reusable logger
Create utils/logger.ts:
export class Logger {
static info(message: string) {
console.log(`[INFO] ${message}`);
}
static error(message: string) {
console.error(`[ERROR] ${message}`);
}
static warning(message: string) {
console.warn(`[WARNING] ${message}`);
}
}
Use it in test scripts:
import { Logger } from ‘../utils/logger’;
Logger.info(‘Starting login test’);
Logger.info(‘Entering user credentials’);
Logger.info(‘Validating login result’);
For enterprise projects, consider a structured logging library when logs need timestamps, severity levels, or external collection.
8. Implementing Assertions, Screenshots, and HTML Reporting
Assertions verify whether the actual application behavior matches the expected result.
Playwright provides built-in web-first assertions.
Example:
import { test, expect } from ‘@playwright/test’;
test(‘Verify application homepage’, async ({ page }) => {
await page.goto(‘/’);
await expect(page).toHaveTitle(/Example/);
await expect(
page.getByRole(‘heading’, { name: ‘Welcome’ })
).toBeVisible();
});
Playwright automatically retries web-first assertions until they pass or reach their timeout.
Screenshot implementation
test(‘Capture homepage screenshot’, async ({ page }) => {
await page.goto(‘/’);
await page.screenshot({
path: ‘screenshots/homepage.png’,
fullPage: true
});
});
Create the screenshots directory before using this explicit path.
For failure screenshots, the configuration already includes:
screenshot: ‘only-on-failure’
HTML reporting
Run:
npx playwright test
Open the generated HTML report:
npx playwright show-report
The HTML report provides:
- Passed test cases.
- Failed test cases.
- Execution duration.
- Error details.
- Screenshots and attachments.
- Browser-specific results.
For debugging, Playwright Trace Viewer is also useful:
npx playwright show-trace trace.zip
9. API Testing, Parallel Execution, and Cross-Browser Testing
A modern Playwright framework should support both UI and API testing.
API testing example
Create tests/api.spec.ts:
import { test, expect } from ‘@playwright/test’;
test(‘Verify GET API response’, async ({ request }) => {
const response = await request.get(
‘https://jsonplaceholder.typicode.com/users/1’
);
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.id).toBe(1);
expect(data.name).toBeTruthy();
});
This example validates an API response without launching a browser.
Parallel execution
Playwright supports parallel test execution through workers.
Run tests with four workers:
npx playwright test –workers=4
Parallel execution reduces overall execution time, but tests should not depend on shared mutable data or execution order.
Cross-browser testing
Execute tests in Chromium:
npx playwright test –project=chromium
Execute tests in Firefox:
npx playwright test –project=firefox
Execute tests in WebKit:
npx playwright test –project=webkit
This helps identify browser-specific UI and functionality issues.
10. Integrating Playwright Framework With Jenkins and GitHub Actions
CI/CD integration allows automation tests to execute automatically whenever developers push code or create pull requests.
GitHub Actions integration
Create:
.github/workflows/playwright.yml
name: Playwright Automation 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 test report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v5
with:
name: playwright-report
path: playwright-report/
retention-days: 30
This workflow checks out the repository, installs dependencies and browsers, validates TypeScript, executes tests, and uploads the HTML report.
Use a supported Node.js version and compatible action versions in your project.
Jenkins integration
Create a Jenkinsfile:
pipeline {
agent any
stages {
stage(‘Checkout’) {
steps {
checkout scm
}
}
stage(‘Install Dependencies’) {
steps {
sh ‘npm ci’
}
}
stage(‘Install Browsers’) {
steps {
sh ‘npx playwright install –with-deps’
}
}
stage(‘Type Check’) {
steps {
sh ‘npx tsc –noEmit’
}
}
stage(‘Execute Tests’) {
steps {
sh ‘npx playwright test
}
}
}
post {
always {
archiveArtifacts(
artifacts: ‘playwright-report/**’,
allowEmptyArchive: true
)
}
}
}
The Jenkins agent must have the required system dependencies and permissions to run browser processes.
For larger QA teams, CI/CD pipelines should also support test environment selection, secure credentials, execution schedules, and report retention.
11. Real-World Playwright Framework Project Example
Let’s understand how all these components work together in a real-world e-commerce project.
Project scenario
Suppose an online shopping application has these requirements:
- A user should log in with valid credentials.
- The user should see the homepage after login.
- The user should select a product.
- The user should add the product to the cart.
- The cart should display the selected product.
Complete execution flow
Test Execution
|
v
LoginPage Fixture
|
v
Enter Username and Password
|
v
Click Login
|
v
Validate Homepage
|
v
Select Product
|
v
Add Product to Cart
|
v
Validate Cart
|
v
Create a product test
Create tests/product.spec.ts:
import { test, expect } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
import { HomePage } from ‘../pages/HomePage’;
import { environment } from ‘../config/environment’;
test(‘Verify product selection and cart’, async ({ page }) => {
const loginPage = new LoginPage(page);
const homePage = new HomePage(page);
// Navigate to login
await loginPage.navigate();
// Login to application
await loginPage.login(
environment.username,
environment.password
);
// Verify homepage
await expect(homePage.heading).toBeVisible();
// Select product
await homePage.selectProduct();
// Open shopping cart
await homePage.openCart();
// Verify cart page
await expect(page).toHaveURL(/cart/);
});
This is an illustrative workflow. Actual product and cart locators should be implemented according to the application’s HTML structure.
Add package.json execution scripts
Add these scripts to your 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”
}
}
Execute the complete framework
Install dependencies:
npm install
Run TypeScript validation:
npm run typecheck
Execute all browser tests:
npm test
Execute tests in headed mode:
npm run test:headed
Execute only Chromium tests:
npm run test:chrome
Open the HTML report:
npm run report
Expected execution result
A successful test execution should display output similar to:
Running 3 tests
✓ login.spec.ts
✓ product.spec.ts
✓ api.spec.ts
3 passed
To open the HTML report:
npx playwright show-report
The exact test count and output depend on the test files in your project.
12. Common Playwright Framework Design Mistakes and Best Practices
When implementing Playwright framework design from scratch, beginners and experienced automation engineers can make several mistakes.
Common mistakes
1. Writing all automation logic in one test file
This creates duplicate code and makes maintenance difficult.
Solution: Separate page objects, fixtures, utilities, and test specifications.
2. Using hardcoded credentials
Hardcoded credentials create security risks.
Solution: Use environment variables and CI/CD secrets.
3. Using unnecessary fixed waits
Example:
await page.waitForTimeout(5000);
Fixed waits slow down execution and can still produce flaky tests.
Solution: Use Playwright’s automatic waiting and web-first assertions.
4. Creating tightly coupled page objects
Page objects should represent meaningful application components and expose reusable actions.
Solution: Keep page objects focused and avoid mixing test assertions with unrelated business logic.
5. Ignoring test isolation
Tests that depend on previous tests can fail when executed in parallel.
Solution: Create independent test data and use isolated browser contexts.
6. Ignoring reporting and debugging
Without screenshots, traces, and useful logs, debugging becomes difficult.
Solution: Configure failure screenshots, trace retention, and HTML reporting.
Enterprise framework design best practices
- Follow the Single Responsibility Principle.
- Use TypeScript interfaces and types where appropriate.
- Prefer accessible locators such as getByRole() and getByLabel().
- Reuse fixtures for common dependencies.
- Keep test data separate from automation logic.
- Use independent tests.
- Implement environment-specific configuration.
- Validate TypeScript during CI execution.
- Use parallel execution after validating test isolation.
- Review framework changes through Git pull requests.
- Avoid unnecessary abstraction and excessive inheritance.
- Maintain documentation for framework setup and execution.
These practices help QA teams maintain reliable automation suites as application functionality grows.
13. FAQs: Playwright Framework Design From Scratch
1. What is Playwright framework design from scratch?
Playwright framework design from scratch means creating a structured automation testing solution using Playwright without depending on an existing custom framework.
It includes configuration, page objects, fixtures, test data, utilities, assertions, reporting, and CI/CD integration.
2. Is Playwright framework design from scratch suitable for beginners?
Yes. Beginners can start with a small framework containing a configuration file, a few page objects, and basic test scripts.
After understanding the fundamentals, they can add fixtures, API testing, cross-browser execution, and reporting.
3. What are the benefits of building a Playwright framework from scratch?
The major benefits include:
- Better code reusability.
- Improved test maintainability.
- Reduced duplicate code.
- Easier debugging.
- Consistent test execution.
- Better CI/CD integration.
- Scalable automation architecture.
4. Which programming language is best for Playwright framework development?
TypeScript is an excellent choice for professional Playwright automation projects because it provides static typing, interfaces, better editor support, and improved code maintainability.
JavaScript is also fully supported.
5. Is Page Object Model mandatory in Playwright?
No. Playwright does not require Page Object Model.
However, POM is useful for applications with multiple pages and reusable interactions. It helps separate application-specific interactions from test scenarios.
6. Can we perform API and UI testing in the same Playwright framework?
Yes. Playwright supports both UI automation and API testing through its browser and API request capabilities.
Combining these testing approaches can improve test coverage and reduce unnecessary UI interactions.
7. How do we generate Playwright HTML reports?
Configure the HTML reporter in playwright.config.ts:
reporter: [
[‘html’, { open: ‘never’ }]
]
Run the tests and execute:
npx playwright show-report
8. Can Playwright execute tests in multiple browsers?
Yes. Playwright supports Chromium, Firefox, and WebKit.
You can configure browser projects and execute the same test suite across multiple browser engines.
9. How do we integrate Playwright with Jenkins?
Create a Jenkins pipeline that checks out the code, installs npm dependencies, installs Playwright browsers, runs TypeScript validation, executes automated tests, and archives test reports.
10. How can we make a Playwright framework scalable for enterprise projects?
Use modular architecture, reusable fixtures, environment management, independent test data, API utilities, cross-browser projects, centralized reporting, and CI/CD pipelines.
Also, establish coding standards and framework maintenance practices across the QA team.
