1. Introduction
Playwright is a modern end-to-end testing framework used to automate web applications across different browsers. It supports Chromium, Firefox, and WebKit and provides powerful features such as automatic waiting, browser isolation, parallel execution, API testing, and built-in reporting.
For beginners entering QA automation, learning Playwright is a valuable way to develop practical browser automation skills.
However, learning individual commands is not enough. You also need to understand how to create a project, organize test scripts, configure browsers, manage test data, write reusable methods, and generate execution reports.
This is why Playwright test framework setup for beginners is an important starting point.
In this tutorial, we will build a Playwright automation framework using TypeScript from scratch. We will cover installation, project structure, the first test case, Page Object Model, locators, assertions, reporting, debugging, and CI/CD integration.
By the end, you will understand how to create and execute a basic Playwright framework that can be extended for real-world testing projects.
2. Prerequisites for Playwright Framework Setup
Before starting the Playwright framework setup, install the required software.
| Tool | Purpose |
| Node.js | Runs JavaScript and TypeScript tooling. |
| npm | Installs and manages dependencies. |
| Visual Studio Code | Code editor for automation development. |
| TypeScript | Provides type-safe test development. |
| Playwright | Automates browser testing. |
| Git | Manages source code versions. |
Step 1: Install Node.js
Visit the official website:
Download and install a supported LTS version.
Verify the installation:
node -v
npm -v
You should see the installed Node.js and npm versions.
Step 2: Install Visual Studio Code
Download VS Code:
VS Code is a popular editor for Playwright development because it provides TypeScript support, IntelliSense, debugging, and integrated terminal access.
Step 3: Install Git
Download Git:
Verify the installation:
git –version
Git helps you maintain your automation framework and share your code through GitHub.
3. Install Playwright and Create Your First Project
Now let’s create a Playwright TypeScript project.
Step 1: Create a Project Folder
Open the terminal and execute:
mkdir playwright-beginner-project
cd playwright-beginner-project
This creates a new directory for your automation framework.
Step 2: Initialize Playwright
Run:
npm init playwright@latest
The Playwright installer will ask a few questions.
Choose the following options:
| Installation Question | Recommended Selection |
| TypeScript or JavaScript | TypeScript |
| Tests folder name | tests |
| Add GitHub Actions workflow | Yes |
| Install Playwright browsers | Yes |
Playwright automatically generates the initial project structure and configuration.
Step 3: Verify Installation
Run:
npx playwright –version
If the command displays the installed Playwright version, the installation is successful.
Step 4: Install Browsers
If you did not install browsers during initialization, execute:
To install a specific browser:
npx playwright install chromium
You are now ready to write your first automation test.
4. Understand the Playwright Project Structure
A clean project structure helps beginners understand where different automation components belong.
After initialization, your project will contain files similar to the following:
playwright-beginner-project/
│
├── tests/
│ └── example.spec.ts
│
├── pages/
│
├── utils/
│
├── test-data/
│
├── playwright.config.ts
│
├── package.json
│
├── package-lock.json
│
├── tsconfig.json
│
└── .github/
└── workflows/
└── playwright.yml
The pages, utils, and test-data folders can be created as your project grows.
Explanation of Each Component
| Component | Responsibility |
| tests | Stores automation test cases. |
| pages | Stores reusable page classes. |
| utils | Contains common helper methods. |
| test-data | Stores test input data. |
| playwright.config.ts | Defines framework settings. |
| package.json | Manages dependencies and commands. |
| tsconfig.json | Configures TypeScript. |
| .github | Contains CI/CD workflows. |
For a beginner, start with a simple project. Introduce additional folders when your test suite requires them.
5. Write and Execute Your First Playwright Test
Let’s create a simple browser automation test.
We will use a public demonstration website, https://playwright.dev/, to verify that the Playwright documentation homepage loads correctly.
Create tests/homepage.spec.ts:
import { test, expect } from ‘@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();
});
Understand the Code
1. Import Playwright methods
import { test, expect } from ‘@playwright/test’;
test defines the test case.- expect validates the expected result.
2. Create the test
test(‘Verify Playwright homepage’, async ({ page }) => {
The page fixture represents a browser tab.
3. Navigate to the website
await page.goto(‘https://playwright.dev/’);
This opens the Playwright documentation website.
4. Validate the page title
await expect(page).toHaveTitle(/Playwright/);
This checks whether the title contains the word Playwright.
5. Verify the Get started link
await expect(
page.getByRole(‘link’, {
name: ‘Get started’
})
).toBeVisible();
This confirms that the expected link is visible.
Execute Your First Test
Run:
npx playwright test tests/homepage.spec.ts
Expected result
The test should pass when the homepage loads successfully, its title matches the expected pattern, and the Get started link is visible.
You have now successfully created your first Playwright automation test.
6. Configure Playwright Framework Settings
The playwright.config.ts file controls how your automation tests execute.
It allows you to configure browsers, base URLs, timeouts, parallel execution, retries, and reporting.
Open playwright.config.ts and update it:
import { defineConfig, devices } from ‘@playwright/test’;
export default defineConfig({
testDir: ‘./tests’,
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 2 : undefined,
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
],
use: {
baseURL: ‘https://playwright.dev/’,
trace: ‘on-first-retry’,
screenshot: ‘only-on-failure’,
video: ‘retain-on-failure’
},
projects: [
{
name: ‘chromium’,
use: { …devices[‘Desktop Chrome’] }
},
{
name: ‘firefox’,
use: { …devices[‘Desktop Firefox’] }
},
{
name: ‘webkit’,
use: { …devices[‘Desktop Safari’] }
}
]
});
Important Configuration Options
| Option | Description |
| testDir | Defines the test directory. |
| fullyParallel | Enables independent tests to run in parallel. |
| retries | Specifies how many times failed tests are retried. |
| workers | Controls the number of parallel workers. |
| baseURL | Defines the application URL. |
| timeout | Controls the maximum test duration. |
| reporter | Configures test reports. |
| trace | Captures execution traces. |
| screenshot | Controls screenshot capture. |
| projects | Defines browser configurations. |
Configure Timeouts
You can configure test and assertion timeouts:
export default defineConfig({
timeout: 30000,
expect: {
timeout: 5000
}
});
The test timeout controls the overall test duration, while the assertion timeout controls how long web-first assertions retry.
Avoid increasing timeouts unnecessarily. First investigate slow application responses and unstable locators.
Run Tests Across Browsers
Execute Chromium:
npx playwright test –project=chromium
Execute Firefox:
npx playwright test –project=firefox
Execute WebKit:
npx playwright test –project=webkit
Cross-browser testing helps identify application compatibility problems before release.
7. Implement Page Object Model (POM)
When you start writing multiple test cases, you may notice that the same locators and browser interactions are repeated.
For example, login functionality may be required in login, dashboard, and order-management tests.
Instead of repeating login code, use the Page Object Model design pattern.
POM separates page interactions from test scenarios and improves framework maintainability.
Step 1: Create a Login Page
Create a folder named pages.
Inside it, create LoginPage.ts:
import { Page, Locator } from ‘@playwright/test’;
export class LoginPage {
readonly email: Locator;
readonly password: Locator;
readonly loginButton: Locator;
constructor(private page: Page) {
this.email = page.getByLabel(‘Username’);
this.password = page.getByLabel(‘Password’);
this.loginButton = page.getByRole(
‘button’,
{ name: ‘Login’ }
);
}
async navigate() {
await this.page.goto(‘/login’);
}
async login(username: string, password: string) {
await this.email.fill(username);
await this.password.fill(password);
await this.loginButton.click();
}
}
This page class contains:
- Login page locators.
- Navigation method.
- Login action method.
The example assumes that your application has accessible Username and Password labels and a Login button.
Step 2: Create a Login Test
Create tests/login.spec.ts:
import { test, expect } from ‘@playwright/test’;
import { LoginPage } from ‘../pages/LoginPage’;
test(‘Verify successful login’, async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.navigate();
await loginPage.login(
‘test@example.com’,
‘Password123’
);
await expect(page).toHaveURL(/dashboard/);
});
Benefits of POM
- Reduces duplicate code.
- Improves readability.
- Makes locator maintenance easier.
- Encourages reusable methods.
- Separates business validation from page interactions.
For a deeper explanation, read the TechSarvam article on Playwright TypeScript Page Object Model and the pillar guide Playwright Framework Design.
8. Understand Playwright Locators and Assertions
Locators identify elements on a web page. Assertions verify whether the application behaves as expected.
Learning these concepts is essential for beginners.
Common Playwright Locators
1. getByRole()
Locates elements using their accessible roles.
await page.getByRole(‘button’, {
name: ‘Submit’
}).click();
2. getByLabel()
Locates form fields using associated labels.
await page.getByLabel(‘Email’)
.fill(‘test@example.com’);
3. getByText()
Locates elements using visible text.
await page.getByText(‘Welcome Back’)
.click();
4. getByTestId()
Locates elements using testing attributes.
await page.getByTestId(‘login-button’)
.click();
Common Playwright Assertions
await expect(page).toHaveTitle(/Dashboard/);
await expect(page).toHaveURL(/dashboard/);
await expect(
page.getByRole(‘heading’, {
name: ‘Dashboard’
})
).toBeVisible();
await expect(
page.getByRole(‘button’, {
name: ‘Logout’
})
).toBeEnabled();
Why Use Web-First Assertions?
Playwright web-first assertions automatically retry until the expected condition is satisfied or the assertion timeout is reached.
Avoid this approach:
await page.waitForTimeout(5000);
Prefer:
await expect(
page.getByText(‘Login Successful’)
).toBeVisible();
Fixed waits increase execution time and can still fail if an application takes longer than expected.
Beginner tip: Prefer role-based and label-based locators because they represent how users interact with an application. Use test IDs when a stable testing identifier is needed.
9. Reporting and Debugging
After executing test cases, you need to understand whether they passed or failed.
Playwright provides built-in reporting and debugging tools.
9.1 Generate an HTML Report
Configure the reporter:
reporter: [
[‘list’],
[‘html’, { open: ‘never’ }]
]
npx playwright test
Open the report:
npx playwright show-report
The HTML report displays passed tests, failed tests, execution duration, and failure details.
9.2 Capture Screenshots
Configure:
use: {
screenshot: ‘only-on-failure’
}
Playwright automatically captures screenshots when tests fail.
9.3 Use Trace Viewer
Configure:
use: {
trace: ‘on-first-retry’
}
npx playwright test
Trace Viewer helps you inspect:
- Browser actions.
- DOM snapshots.
- Network requests.
- Locator failures.
- Execution timing.
You can also debug tests using:
npx playwright test –debug
Common Beginner Problems
| Problem | Solution |
| Browser executable missing | Run npx playwright install. |
| Test cannot find element | Check the locator and page state. |
| Test timeout | Investigate synchronization and application response. |
| Module not found | Verify imports and dependencies. |
| Test passes locally but fails in CI | Check environment variables and browser setup. |
| HTML report missing | Verify reporter configuration and test execution. |
10. Integrate Playwright with GitHub Actions
Continuous integration allows automation tests to execute automatically when developers push code changes.
GitHub Actions is a convenient starting point for beginners.
Create:
.github/workflows/playwright.yml
name: Playwright Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
– name: Checkout Code
uses: actions/checkout@v4
– name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
– name: Install Dependencies
run: npm ci
– name: Install Browsers
run: npx playwright install –with-deps
– name: Run Tests
run: npx playwright test
– name: Upload HTML Report
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
retention-days: 30
Commit your workflow and push it to GitHub.
GitHub Actions will execute the workflow on pushes and pull requests targeting the main branch.
For a real application, configure the base URL and any required credentials through GitHub Actions secrets and environment variables.
This is an important skill for QA engineers because modern automation frameworks are commonly integrated into CI/CD pipelines.
11. Playwright Best Practices and Common Mistakes
When learning Playwright test framework setup for beginners, following good coding practices from the beginning will make your framework easier to maintain.
Recommended Best Practices
- Use TypeScript: Take advantage of type checking and IntelliSense.
- Follow POM: Keep page interactions separate from test scenarios.
- Use reliable locators: Prefer getByRole(), getByLabel(), and getByTestId().
- Avoid fixed waits: Use auto-waiting and web-first assertions.
- Keep tests independent: Each test should execute without depending on another test.
- Separate test data: Store reusable test inputs outside test scripts.
- Use Git: Maintain your automation code in a GitHub repository.
- Generate reports: Use HTML reports and Trace Viewer for debugging.
- Manage credentials securely: Never commit passwords or API tokens.
- Start simple: Add advanced architecture components as your project grows.
Common Mistakes
| Mistake | Recommended Solution |
| Writing all code in one file | Separate tests and page objects. |
| Hard-coding URLs | Use baseURL configuration. |
| Using unnecessary XPath | Prefer accessible locators. |
| Adding fixed waits | Use web-first assertions. |
| Ignoring failed tests | Investigate traces and screenshots. |
| Sharing test data | Use independent test records. |
| Committing node_modules | Add it to .gitignore. |
| Ignoring CI failures | Review pipeline logs and artifacts. |
12. FAQs and Playwright Interview Questions
Q1. What is Playwright test framework setup for beginners?
It is the process of installing Playwright, configuring TypeScript, creating a project structure, writing test cases, and setting up reporting and browser execution.
Q2. How do I get started with Playwright test framework setup for beginners?
Install Node.js and VS Code, run npm init playwright@latest, select TypeScript, install browsers, and create your first test case.
Q3. What are the benefits of Playwright test framework setup for beginners?
It helps beginners learn browser automation, reusable test development, cross-browser testing, debugging, reporting, and CI/CD integration.
Q4. Is Playwright suitable for freshers?
Yes. Playwright provides an approachable test runner, automatic waiting, built-in assertions, and TypeScript support. Beginners can gradually learn advanced framework concepts.
Q5. Which programming language is best for Playwright?
Playwright supports TypeScript, JavaScript, Python, Java, and .NET. TypeScript is a popular choice for browser automation projects because of its type safety and development tools.
Q6. What is the purpose of playwright.config.ts?
It manages test execution settings such as test directories, browsers, base URLs, timeouts, retries, workers, and reporting.
Q7. What is Page Object Model in Playwright?
POM is a design pattern that separates page locators and reusable browser interactions from test scenarios.
Q8. How do you run a specific Playwright test?
Use:
npx playwright test tests/login.spec.ts
Q9. How do you generate Playwright reports?
Execute the test suite and run:
npx playwright show-report
Q10. How do you debug a failed Playwright test?
Use Playwright Inspector, HTML reports, screenshots, and Trace Viewer to investigate the failure.
