1. Introduction to the Playwright JavaScript Framework
Modern web applications require continuous testing to maintain quality and reliability. Manual testing becomes difficult when applications receive frequent updates, new features, and bug fixes.
A Playwright JavaScript framework helps QA Automation Engineers and SDETs automate web application testing using JavaScript and Playwright.
Instead of writing individual automation scripts, a framework provides a structured approach to organizing test cases, page objects, reusable functions, test data, configuration, and reports.
The Playwright JavaScript framework supports:
- End-to-end browser automation.
- Cross-browser testing.
- API testing.
- Data-driven testing.
- Parallel test execution.
- Regression testing.
- CI/CD integration.
- Automated test reporting.
In this tutorial, we will build a reusable Playwright Automation Framework from scratch using JavaScript. We will cover framework architecture, Page Object Model, fixtures, configuration, authentication, API testing, debugging, and continuous integration.
2. What Is an Automation Framework, and Why Use Playwright with JavaScript?
An automation framework is a collection of guidelines, reusable components, libraries, and tools that help testers develop and maintain automated test cases.
A framework reduces duplicate code and makes test execution easier.
Playwright is an open-source browser automation framework that supports Chromium, Firefox, and WebKit.
JavaScript is a natural choice because Playwright provides first-class JavaScript support and works with Node.js.
Benefits of a Playwright JavaScript Framework
- Reusable components: Page Object Model reduces duplicate code.
- Auto-waiting: Playwright automatically waits for elements to become actionable.
- Cross-browser testing: Execute tests across Chromium, Firefox, and WebKit.
- Parallel execution: Run independent test cases simultaneously.
- API testing: Validate backend services alongside browser workflows.
- Reporting: Generate HTML reports with execution details.
- CI/CD integration: Execute automated tests during application deployments.
For Selenium testers, learning Playwright is also an opportunity to understand modern browser automation, web-first assertions, fixtures, and browser contexts.
3. Prerequisites and Project Setup
Before building the Playwright JavaScript framework, install the following:
| Tool | Purpose |
| Node.js LTS | JavaScript runtime |
| npm | Dependency management |
| Visual Studio Code | Code editor |
| Playwright Test | Automation and test execution |
| Git | Version control |
Download Node.js from https://nodejs.org/.
Verify the installation:
node -v
npm -v
Create a new project:
mkdir playwright-framework
cd playwright-framework
npm init -y
Install Playwright Test:
npm install -D @playwright/test
Install browser binaries:
Playwright Test includes browser automation, fixtures, assertions, and a test runner.
4. Installing Playwright and Understanding the Project Structure
After installation, create a basic test directory.
playwright-framework/
│
├── tests/
│ └── example.spec.js
│
├── playwright.config.js
├── package.json
└── package-lock.json
Create tests/example.spec.js:
const { test, expect } = require(‘@playwright/test’);
test(‘Verify Playwright homepage’, async ({ page }) => {
await page.goto(‘https://playwright.dev/’);
await expect(page).toHaveTitle(/Playwright/);
await expect(
page.getByRole(‘link’, {
name: ‘Get started’
})
).toBeVisible();
});
Run the test:
npx playwright test
This confirms that your Playwright installation is working.
5. Designing a Scalable Playwright Framework Folder Structure
For a real-world automation project, keeping every test in one folder is not sufficient.
A scalable framework separates test cases, page classes, utilities, test data, and configuration.
Recommended structure:
playwright-framework/
│
├── tests/
│ ├── login.spec.js
│ ├── dashboard.spec.js
│ └── api.spec.js
│
├── pages/
│ ├── LoginPage.js
│ └── DashboardPage.js
│
├── fixtures/
│ └── testFixture.js
│
├── utils/
│ └── helpers.js
│
├── test-data/
│ └── users.json
│
├── playwright.config.js
├── package.json
├── .env
└── .gitignore
Understanding framework components
- Tests: Store test scenarios and assertions.
- Pages: Store locators and reusable page actions.
- Fixtures: Manage test setup and reusable dependencies.
- Utils: Store common helper functions.
- Test data: Store input values and test scenarios.
- Configuration: Control browsers, timeouts, retries, and reporting.
This architecture makes the Playwright JavaScript framework easier to maintain as the number of test cases increases.
6. Configuring playwright.config.js and Package Scripts
The configuration file controls how tests execute.
Create playwright.config.js:
const { defineConfig } = require(‘@playwright/test’);
module.exports = defineConfig({
testDir: ‘./tests’,
timeout: 30000,
expect: {
timeout: 5000
},
fullyParallel: true,
retries: 1,
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
],
use: {
baseURL: ‘https://the-internet.herokuapp.com’,
headless: true,
screenshot: ‘only-on-failure’,
trace: ‘on-first-retry’
},
projects: [
{
name: ‘chromium’,
use: { browserName: ‘chromium’ }
},
{
name: ‘firefox’,
use: { browserName: ‘firefox’ }
},
{
name: ‘webkit’,
use: { browserName: ‘webkit’ }
}
]
});
Configure npm scripts
Update the scripts section in package.json:
{
“scripts”: {
“test”: “playwright test”,
“test:headed”: “playwright test –headed,
“test:debug”: “playwright test –debug,
“test:ui”: “playwright test –ui,
“test:chromium”: “playwright test –project=chromium,
“report”: “playwright show-report”
}
}
Execute tests using:
npm test
npm run test:headed
npm run test:chromium
npm run report
The configuration centralizes execution settings, making it easier to manage multiple environments and browsers.
7. Implementing Page Object Model and Reusable Page Classes
Page Object Model (POM) is one of the most important design patterns used in automation frameworks.
It separates page interactions from test logic.
Create pages/LoginPage.js:
class LoginPage {
constructor(page) {
this.page = page;
this.username = page.locator(‘#username’);
this.password = page.locator(‘#password’);
this.loginButton = page.locator(
‘button[type=”submit”]’
);
this.message = page.locator(‘#flash’);
}
async open() {
await this.page.goto(‘/login’);
}
async login(username, password) {
await this.username.fill(username);
await this.password.fill(password);
await this.loginButton.click();
}
}
module.exports = LoginPage;
Create tests/login.spec.js:
const { test, expect } = require(‘@playwright/test’);
const LoginPage = require(‘../pages/LoginPage’);
test(‘Verify successful login’, async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.open();
await loginPage.login(
‘tomsmith’,
‘SuperSecretPassword!’
);
await expect(loginPage.message).toContainText(
‘You logged into a secure area!’
);
});
Advantages of POM:
- Reduces duplicate code.
- Improves readability.
- Simplifies locator maintenance.
- Encourages reusable components.
- Supports larger regression testing suites.
8. Creating Fixtures, Test Data, Utilities, and Environment Configuration
Fixtures help manage reusable test dependencies.
Create fixtures/testFixture.js:
const base = require(‘@playwright/test’);
const LoginPage = require(‘../pages/LoginPage’);
exports.test = base.test.extend({
loginPage: async ({ page }, use) => {
const loginPage = new LoginPage(page);
await use(loginPage);
}
});
exports.expect = base.expect;
Now use the custom fixture in a test:
const { test, expect } = require(‘../fixtures/testFixture’);
test(‘Login using custom fixture‘, async ({ loginPage }) => {
await loginPage.open();
await loginPage.login(
‘tomsmith’,
‘SuperSecretPassword!’
);
await expect(loginPage.message).toContainText(
‘You logged into a secure area!’
);
});
Manage test data
Create test-data/users.json:
{
“validUser”: {
“username”: “tomsmith”,
“password”: “SuperSecretPassword!”
}
}
Import the data:
const users = require(‘../test-data/users.json’);
console.log(users.validUser.username);
Environment configuration
Install dotenv:
npm install dotenv
Create .env:
BASE_URL=https://the-internet.herokuapp.com
Load it in playwright.config.js:
require(‘dotenv’).config();
const { defineConfig } = require(‘@playwright/test’);
module.exports = defineConfig({
testDir: ‘./tests’,
use: {
baseURL: process.env.BASE_URL
}
});
Add .env to .gitignore. Never commit production credentials or authentication tokens.
9. Adding Assertions, API Testing, Authentication, and Cross-Browser Testing
A good Playwright JavaScript framework should validate both frontend and backend functionality.
Browser assertions
await expect(page).toHaveURL(/secure/);
await expect(
page.locator(‘#flash’)
).toContainText(‘You logged into a secure area!’);
Playwright web-first assertions automatically retry until the expected condition is satisfied or the timeout expires.
API testing example
Create tests/api.spec.js:
const { test, expect } = require(‘@playwright/test’);
test(‘Validate user API’, 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).toHaveProperty(’email’);
});
Authentication using saved browser state
For applications requiring login before every test, Playwright supports reusable authentication state.
First, generate a storage state using a dedicated setup script or setup project:
const { chromium } = require(‘@playwright/test’);
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(‘YOUR_APPLICATION_LOGIN_URL’);
// Complete the application’s login workflow here.
await context.storageState({
path: ‘playwright/.auth/user.json’
});
await browser.close();
})();
Configure authenticated tests to use:
use: {
storageState: ‘playwright/.auth/user.json’
}
The login workflow must actually complete before saving the state. Add the authentication file to .gitignore because it may contain sensitive cookies and tokens.
Cross-browser testing
The three projects configured earlier allow the same test suite to run in Chromium, Firefox, and WebKit.
Execute one browser:
npx playwright test –project=chromium
Execute all configured browsers:
npx playwright test
10. Configuring Parallel Execution, Retries, Screenshots, Traces, and HTML Reports
A scalable Playwright Automation Framework should support efficient execution and debugging.
Important configuration properties include:
| Property | Purpose |
| fullyParallel | Allows independent tests to run in parallel |
| workers | Controls parallel worker count |
| retries | Retries failed tests |
| screenshot | Captures screenshots |
| trace | Records execution details |
| reporter | Generates test reports |
Example:
module.exports = defineConfig({
workers: 4,
retries: 2,
use: {
screenshot: ‘only-on-failure’,
trace: ‘retain-on-failure’,
video: ‘retain-on-failure’
},
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
]
});
Run tests:
npx playwright test
Open the HTML report:
npx playwright show-report
For debugging:
npx playwright test –debug
Avoid increasing retries simply to hide flaky tests. Investigate synchronization issues, unstable test data, and application defects.
11. Integrating the Framework with GitHub Actions and Jenkins
Continuous integration helps teams execute automated tests whenever code changes.
Create .github/workflows/playwright.yml:
name: Playwright Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v4
– uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
– run: npm ci
– run: npx playwright install –with-deps
– run: npm test
– uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/
Use a Node.js version supported by your installed Playwright release.
For Jenkins, 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(‘Execute Tests’) {
steps {
sh ‘npm test’
}
}
}
post {
always {
archiveArtifacts(
artifacts: ‘playwright-report/**’,
allowEmptyArchive: true
)
}
}
}
The Jenkins agent must have the required operating system dependencies and permissions.
12. Real-World Playwright Framework Example
Consider an e-commerce application with login, product search, cart, and checkout functionality.
A typical regression suite can include:
| Test scenario | Validation |
| User login | Successful authentication |
| Invalid login | Appropriate error message |
| Product search | Relevant products displayed |
| Add to cart | Product added successfully |
| Checkout | Order confirmation displayed |
| API validation | Backend response is correct |
Organize these scenarios into separate test files and reusable page classes.
For example, the login page can handle authentication, the product page can manage product selection, and the checkout page can validate order completion.
This separation makes the framework easier to expand when new application features are introduced.
13. Common Framework Design Mistakes and Best Practices
| Common mistake | Recommended approach |
| Writing all code in one file | Separate tests and page objects |
| Duplicating locators | Use reusable page classes |
| Hardcoding credentials | Use environment variables |
| Using fixed waits | Use auto-waiting and assertions |
| Sharing test data between tests | Create independent test data |
| Ignoring failed reports | Enable traces and screenshots |
| Running only Chrome tests | Configure multiple browsers |
| Ignoring CI failures | Review pipeline logs and artifacts |
Follow these additional recommendations:
- Keep test cases independent.
- Use meaningful test names.
- Prefer accessible locators.
- Keep configuration centralized.
- Use fixtures for reusable setup.
- Maintain separate test data.
- Review failed tests regularly.
- Keep dependencies and browser versions consistent.
14. Playwright JavaScript Framework Interview Questions
Q1. What is a Playwright JavaScript framework?
It is a structured automation solution built using Playwright and JavaScript to manage browser tests, reusable components, test data, configuration, and reporting.
Q2. What is Page Object Model?
POM is a design pattern that separates page interactions from test cases to improve maintainability and reusability.
Q3. What are Playwright fixtures?
Fixtures provide reusable dependencies and setup/teardown functionality for test cases.
Q4. What is playwright.config.js?
It is the central configuration file used to define test directories, browsers, retries, timeouts, reporters, and other execution settings.
Q5. How do you execute tests in parallel?
Use Playwright Test’s worker configuration and parallel execution features.
Q6. How do you handle authentication?
Use login setup scripts or setup projects to generate and reuse browser storage state.
Q7. Can Playwright support API and UI testing in the same framework?
Yes. Playwright supports browser automation and API requests through its test fixtures.
Q8. How do you integrate Playwright with CI/CD?
Configure a pipeline to install Node.js dependencies, install browsers, execute tests, and publish reports.
Placement-oriented interview preparation tips
For Indian QA Automation and SDET interviews, prepare practical explanations of:
- Framework architecture and folder structure.
- Page Object Model implementation.
- Custom fixtures and hooks.
- Data-driven automation.
- API and UI integration.
- Cross-browser execution.
- GitHub Actions and Jenkins.
- Handling flaky tests and debugging failures.
Practice explaining one complete project from test planning to CI/CD execution instead of memorizing only definitions.
15. Frequently Asked Questions (FAQs)
1. What is Playwright JavaScript framework?
It is an automation framework that uses Playwright and JavaScript to automate web applications, validate functionality, and execute regression tests.
2. What are the benefits of Playwright JavaScript framework?
It provides reusable components, cross-browser testing, auto-waiting, API testing, parallel execution, reporting, and CI/CD integration.
3. How do I get started with Playwright JavaScript framework?
Install Node.js, initialize an npm project, install Playwright Test, create a configuration file, and write your first JavaScript test.
4. Is Playwright JavaScript framework suitable for beginners?
Yes. Beginners with basic JavaScript knowledge can learn browser automation first and gradually develop reusable framework components.
5. Can we build a framework without TypeScript?
Yes. Playwright fully supports JavaScript. You can create a complete framework using .js files.
6. Is Playwright suitable for enterprise automation?
Yes. Its fixtures, parallel execution, browser support, API testing, and CI/CD capabilities make it suitable for large automation projects when designed and maintained properly.
7. Can Playwright replace Selenium?
Playwright can replace Selenium in suitable projects, but the decision depends on application requirements, supported browsers, existing infrastructure, and language ecosystem.
