A–Z Playwright Commands & APIs
A
await page.goto(url)– Navigate to a pageawait page.addInitScript()– Add script before page loadsawait page.authenticate()– HTTP authentication
B
npx playwright build-deps– Install system dependenciesbrowser = await chromium.launch()– Launch browserbrowser.newContext()– Create isolated browser context
C
npx playwright codegen– Generate test code automaticallycontext.newPage()– Open new pagepage.click(selector)– Click elementpage.check(selector)– Check checkbox
D
npx playwright debug– Debug testspage.dblclick(selector)– Double clickpage.dragAndDrop(source, target)
E
expect(locator).toBeVisible()– Assertionpage.evaluate()– Run JS in browserpage.exposeFunction()– Expose Node function to browser
F
page.fill(selector, value)– Fill inputpage.focus(selector)page.frame(nameOrUrl)
G
page.getByText()– Locate by textpage.getByRole()– ARIA-based locatorpage.goBack()/page.goForward()
H
page.hover(selector)page.route()– Network mockingpage.waitForResponse()
I
npx playwright install– Install browserspage.isVisible(selector)page.innerText(selector)
J
page.keyboard.press('Enter')page.keyboard.type()
K
page.keyboard.down()/up()
L
page.locator(selector)– Preferred locatorpage.reload()
M
page.mouse.move()page.mouse.click()page.mouse.wheel()
N
npx playwright test– Run testspage.newPage()page.routeFromHAR()
O
page.once('dialog')page.opener()
P
page.pause()– Pause test executionpage.pdf()– Generate PDFpage.press(selector, key)
Q
page.querySelector()(rare, use locator instead)
R
npx playwright test --reporter=htmlpage.route()– Intercept networkpage.reload()
S
page.screenshot()page.selectOption()page.setViewportSize()
T
test()– Define testtest.describe()– Group teststest.beforeEach()/afterEach()
U
page.uncheck(selector)page.url()
V
page.video()– Capture videoexpect().toHaveValue()
W
page.waitForSelector()page.waitForTimeout()(avoid when possible)page.waitForURL()
X
expect(locator).toHaveText()expect(locator).toHaveCount()
Y
page.waitForLoadState('networkidle')
Z
npx playwright show-report– Open HTML report
Most-Used CLI Commands (Quick List)
npx playwright install
npx playwright test
npx playwright test --ui
npx playwright codegen
npx playwright debug
npx playwright show-report
Best Practices
Prefer
locator()overquerySelectorAvoid
waitForTimeout()→ use smart waitsUse ARIA locators (
getByRole) for stable testsUse Page Object Model (POM) for scalability
playwright-automation/
│
├── playwright.config.ts
├── package.json
├── package-lock.json
├── README.md
│
├── tests/
│ ├── login/
│ │ └── login.spec.ts
│ ├── dashboard/
│ │ └── dashboard.spec.ts
│ └── regression/
│ └── regression.spec.ts
│
├── pages/ # Page Object Model (POM)
│ ├── LoginPage.ts
│ ├── DashboardPage.ts
│ └── BasePage.ts
│
├── fixtures/
│ └── testSetup.ts # Custom fixtures
│
├── utils/
│ ├── testData.ts
│ ├── helpers.ts
│ ├── apiHelper.ts
│ └── logger.ts
│
├── test-data/
│ ├── users.json
│ └── config.json
│
├── reports/
│ └── html-report/
│
├── screenshots/
├── videos/
│
├── ci/
│ └── github-actions.yml
│
└── .env
1️⃣ playwright.config.ts
Browser setup, retries, timeouts, reporters
Environment configuration (QA / UAT / PROD)
Parallel execution
use: {
baseURL: process.env.BASE_URL,
screenshot: 'only-on-failure',
video: 'retain-on-failure'
}
2️⃣ tests/ – Test Layer
Contains only test logic
No locators, no UI logic
test('User can login', async ({ page }) => {
await loginPage.login('user', 'password');
});
3️⃣ pages/ – Page Object Model
Encapsulates UI logic and locators.
export class LoginPage {
constructor(private page: Page) {}
async login(user, pass) {
await this.page.fill('#user', user);
await this.page.fill('#pass', pass);
await this.page.click('#login');
}
}
✔ Improves maintainability
✔ Reduces duplication
4️⃣ fixtures/ – Test Setup
Used for:
Login state
Browser context setup
Auth reuse
test.extend({
authenticatedPage: async ({ page }, use) => {
await login(page);
await use(page);
}
});
5️⃣ utils/ – Helpers
Reusable utilities:
API calls
Random data
Date handling
Logging
export function generateEmail() {
return `user_${Date.now()}@test.com`;
}
6️⃣ test-data/
Externalize test data
Supports data-driven testing
{
"username": "testuser",
"password": "Password123"
}
7️⃣ reports/
HTML / Allure reports
Stored for CI/CD review
8️⃣ screenshots/ & videos/
Captured automatically on failures
Used for defect analysis
9️⃣ ci/ – CI/CD Integration
GitHub Actions / Jenkins
- run: npx playwright test
✔ Enables nightly & PR runs
🔟 .env – Environment Config
BASE_URL=https://qa.example.com
Why This Framework Works in Real Projects
✔ Scalable
✔ Easy maintenance
✔ CI/CD ready
✔ Supports UI + API automation
✔ Industry-standard structure
Advanced Enhancements (Optional)
Allure reporting
API + UI hybrid tests
Retry logic for flaky tests
Multi-env execution
Role-based auth storage
“We use Playwright with Page Object Model, custom fixtures, reusable utilities, and CI/CD integration for scalable automation.”
Below is a real-time End-to-End (E2E) Playwright test example using an industry-standard framework (POM + fixtures), exactly how it’s done in real projects.
E2E Scenario
User logs in → navigates to dashboard → creates a record → verifies success
Test Case (E2E Flow)
📁 tests/e2e/user-flow.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';
import { DashboardPage } from '../../pages/DashboardPage';
test('E2E: User login and create record', async ({ page }) => {
const loginPage = new LoginPage(page);
const dashboard = new DashboardPage(page);
// Step 1: Navigate & Login
await loginPage.goto();
await loginPage.login('testuser', 'Password123');
// Step 2: Verify Dashboard
await expect(dashboard.header).toBeVisible();
// Step 3: Create new record
await dashboard.createRecord('Playwright E2E Test');
// Step 4: Validate success
await expect(dashboard.successToast).toHaveText('Record created successfully');
});
Login Page Object
📁 pages/LoginPage.ts
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly username: Locator;
readonly password: Locator;
readonly loginBtn: Locator;
constructor(page: Page) {
this.page = page;
this.username = page.locator('#username');
this.password = page.locator('#password');
this.loginBtn = page.locator('#loginBtn');
}
async goto() {
await this.page.goto('/login');
}
async login(user: string, pass: string) {
await this.username.fill(user);
await this.password.fill(pass);
await this.loginBtn.click();
}
}
Dashboard Page Object
📁 pages/DashboardPage.ts
import { Page, Locator } from '@playwright/test';
export class DashboardPage {
readonly page: Page;
readonly header: Locator;
readonly addButton: Locator;
readonly nameInput: Locator;
readonly saveButton: Locator;
readonly successToast: Locator;
constructor(page: Page) {
this.page = page;
this.header = page.locator('h1:has-text("Dashboard")');
this.addButton = page.locator('#add');
this.nameInput = page.locator('#name');
this.saveButton = page.locator('#save');
this.successToast = page.locator('.toast-success');
}
async createRecord(name: string) {
await this.addButton.click();
await this.nameInput.fill(name);
await this.saveButton.click();
}
}
Playwright Config (E2E-Ready)
📁 playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
retries: 1,
reporter: [['html'], ['list']],
use: {
baseURL: 'https://qa.example.com',
screenshot: 'only-on-failure',
video: 'retain-on-failure'
}
});
Execution Command
npx playwright test
npx playwright show-report
Why This Is a True Real-Time E2E Test
✔ Covers complete user journey
✔ Uses Page Object Model
✔ Assertions at critical checkpoints
✔ Failure evidence (screenshots/video)
✔ CI/CD friendly
implemented E2E tests in Playwright using POM, covering login-to-business-action workflows, with validations, reusable components, and CI integration.
Next Level Enhancements
API setup before UI flow
Auth storage state reuse
Data-driven E2E
Role-based access tests
Parallel execution