This step-by-step, human-friendly guide is designed to help you master Playwright for end-to-end testing. Whether you’re setting up your environment or diving into advanced testing scenarios, this tutorial covers everything you need to know.
Table of Contents
- 1. Intro
- 2. What is Playwright
- 3. Install NodeJS on Windows
- 4. Install VSCode on Windows
- 5. Install NodeJS on Mac
- 6. Install VSCode on Mac
- 7. How To Write Your First Playwright Test Case (with Assertion)
- 8. How To Interact With Web Elements in Playwright
- 9. How To Verify Text in Playwright
- 10. How To Maximize Browser Window (Viewport) in Playwright
- 11. How To Take Screenshots, Videos, and Trace Files in Playwright
- 12. How To Record and Play Scripts (Codegen) in Playwright
- 13. How To Retry Failed Test Cases in Playwright
- 14. Install Playwright in Visual Studio Code
- 15. Handle Dropdown in Playwright and Verify Dropdown Values
- 16. How To Run Playwright Tests from the Command Line (Headed/Headless)
- 17. How To Perform Mouse Hover in Playwright
- 18. How To Upload Files in Playwright
- 19. How To Handle Keyboard Actions in Playwright
- 20. How To Handle Autocomplete / Auto Suggestion in Playwright
- 21. How To Handle Alerts in Playwright
- 22. How To Handle Frames and iframes in Playwright
- 23. How To Handle Multiple Tabs in Playwright
- 24. How To Handle Dynamic Network Calls in Playwright
- 25. How To Read Data from JSON Files (Data-Driven Tests)
- 26. How To Generate Allure Reports in Playwright (with Screenshots)
- 27. Page Object Model in Playwright (with JavaScript)
- 28. How To Push Playwright Tests to GitHub
- 29. How To Run Playwright with Jenkins
- 30. Conclusion
- All Assertions, Actions, and Locator Strategies
1. Intro
This course covers everything you need to know to get started with Playwright using JavaScript:
- Setting up NodeJS and VSCode on Windows and Mac
- Writing your first test
- Interacting with all kinds of elements
- Handling dropdowns, alerts, frames, mouse events, etc.
- Advanced topics like file uploads, keyboard actions, multiple tabs, and data-driven testing
- Generating reports, using Page Object Model (POM), and running tests on CI/CD (Jenkins)
2. What is Playwright
Playwright is an end-to-end testing framework maintained by Microsoft. It allows you to:
- Automate web browsers (Chromium, Firefox, and WebKit)
- Write fast, stable tests in multiple languages (JavaScript/TypeScript, Java, Python, .NET)
- Benefit from auto-wait, parallel execution, built-in reporters, mobile device emulation, etc.
Key Features
- Cross-browser: Works on Chromium, Firefox, WebKit
- Cross-platform: Runs on Windows, Linux, and macOS
- Auto-wait: Automatically waits for elements to be ready
- Powerful tooling: Codegen, Inspector, Trace Viewer, etc.
- Multiple languages: JavaScript, TypeScript, Java, Python, .NET
3. Install NodeJS on Windows
- Download: Go to NodeJS.org and download the LTS version.
- Install: Run the
.msi
file, accept defaults. - Verify:
node -v npm -v
Ensure Node ≥14.
4. Install VSCode on Windows
- Download: Visit the VSCode website.
- Install: Run the
.exe
, accept defaults. - Extensions:
- ESLint
- Prettier
- Playwright Test for VSCode
5. Install NodeJS on Mac
- Download: NodeJS.org →
.pkg
installer for macOS - Install: Follow on-screen prompts, allow permissions.
- Verify:
node -v npm -v
Ensure Node ≥14.
6. Install VSCode on Mac
- Download:
.dmg
from VSCode website - Install: Drag into Applications folder.
- Extensions:
- ESLint
- Prettier
- Playwright Test for VSCode
7. How To Write Your First Playwright Test Case (with Assertion)
Project Initialization
# 1. Create and open a new folder
mkdir playwright-demo
cd playwright-demo
code .
# 2. Initialize project
npm init -y
# 3. Install Playwright
npm i -D @playwright/test
Explanation:
mkdir playwright-demo
creates a new folder.npm init -y
quickly sets uppackage.json
.npm i -D @playwright/test
installs the Playwright test runner.
Sample Test: example.spec.js
// @ts-check
const { test, expect } = require('@playwright/test');
test('My first test', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle('Example Domain');
});
Explanation:
- Line 1:
// @ts-check
for type hints. - Line 2: Imports
test
andexpect
from Playwright. - Line 4: Defines a test named
"My first test"
. - Line 5: Navigates to
example.com
. - Line 6: Verifies page title is
"Example Domain"
.
Run the Test
npx playwright test
8. How To Interact With Web Elements in Playwright
Below is a sample test that logs into a site:
const { test, expect } = require('@playwright/test');
test('Login test', async ({ page }) => {
// 1. Go to application
await page.goto('https://example.com/login');
// 2. Type into fields
await page.fill('#username', 'admin');
await page.fill('#password', 'admin123');
// 3. Click login button
await page.click('button[type="submit"]');
// 4. Verify dashboard is visible
await expect(page.locator('.dashboard')).toBeVisible();
});
Explanation:
- Line 1: Imports test & expect.
- Line 3: Declares a test block.
- Line 5: Navigates to the login page.
- Line 8–9: Fills username & password fields.
- Line 12: Clicks the submit button.
- Line 15: Checks if
.dashboard
is visible.
9. How To Verify Text in Playwright
test('Verify text on page', async ({ page }) => {
await page.goto('https://example.com');
const header = page.locator('h1');
await expect(header).toContainText('Welcome');
});
Explanation:
- Line 1: Declares test named “Verify text on page”.
- Line 2: Navigates to example.com.
- Line 3: Locates
h1
element. - Line 4: Asserts partial text “Welcome”.
10. How To Maximize Browser Window (Viewport) in Playwright
Option 1: In playwright.config.js
module.exports = {
use: {
viewport: { width: 1920, height: 1080 },
},
};
Explanation: Sets the default browser viewport to 1920×1080.
Option 2: Dynamically in Test
test('Set viewport', async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto('https://example.com');
});
Explanation: page.setViewportSize(...)
adjusts the size before loading the site.
11. How To Take Screenshots, Videos, and Trace Files in Playwright
Screenshots & Videos (in playwright.config.js
)
use: {
screenshot: 'only-on-failure', // or 'on', 'off'
video: 'retain-on-failure' // or 'on', 'off'
},
Explanation: Captures screenshots or videos on test failures.
Manual Screenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });
Explanation: Saves a full-page screenshot as screenshot.png
.
Trace Files
use: {
trace: 'on-first-retry', // 'on', 'retain-on-failure', etc.
},
After test run:
npx playwright show-trace trace.zip
Explanation: Opens a trace viewer for step-by-step debugging.
12. How To Record and Play Scripts (Codegen) in Playwright
npx playwright codegen https://example.com
Explanation: Launches a browser + inspector. As you interact, code is generated. You can copy or export it.
13. How To Retry Failed Test Cases in Playwright
In playwright.config.js
:
module.exports = {
retries: 2,
};
Explanation: Each failing test is retried up to 2 times.
Or from CLI:
npx playwright test --retries=2
14. Install Playwright in Visual Studio Code
Option 1: Using Built-in Terminal
npm init playwright@latest
Explanation: Official wizard that sets up a Playwright project (JS/TS).
Option 2: “Playwright Test for VSCode” Extension
- Install from VSCode’s extension panel.
Ctrl/Cmd + Shift + P
→ “Install Playwright.”- Extension auto-configures your project.
15. Handle Dropdown in Playwright and Verify Dropdown Values
test('Select value from dropdown', async ({ page }) => {
await page.goto('https://example.com');
await page.selectOption('#mySelect', 'optionValue');
});
Explanation: page.selectOption(selector, value)
selects an option by its `value`. Or use `{ label: ‘…’ }` to select by label.
16. How To Run Playwright Tests from the Command Line (Headed/Headless)
# Run all tests
npx playwright test
# Run a specific file
npx playwright test file.spec.js
# Headed mode
npx playwright test --headed
# Only Chromium
npx playwright test --project=chromium
Explanation: The `–headed` flag shows the browser, while `–project=chromium` restricts tests to Chromium only.
17. How To Perform Mouse Hover in Playwright
await page.hover('selector-for-menu');
await page.click('selector-for-submenu');
Explanation: Hover over a menu, then click the revealed submenu item.
18. How To Upload Files in Playwright
await page.setInputFiles('input[type="file"]', 'path/to/file.png');
await page.click('#uploadBtn');
Explanation: Sets a file on ``, then clicks the “upload” button.
19. How To Handle Keyboard Actions in Playwright
// Type text
await page.keyboard.type('Hello');
// Press Enter
await page.keyboard.press('Enter');
// Ctrl + A + Backspace
await page.keyboard.down('Control');
await page.keyboard.press('A');
await page.keyboard.up('Control');
await page.keyboard.press('Backspace');
Explanation: Demonstrates typing text, pressing special keys, and combo keys like Ctrl + A + Backspace.
20. How To Handle Autocomplete / Auto Suggestion in Playwright
Approach 1: Arrow Keys
await page.fill('#search', 'Playwright');
await page.keyboard.press('ArrowDown');
await page.keyboard.press('ArrowDown');
await page.keyboard.press('Enter');
Explanation: Fills search input, moves down suggestions, presses Enter.
Approach 2: Wait for Suggestions & Click
await page.fill('#search', 'Playwright');
await page.waitForSelector('.suggestions li');
const suggestions = await page.$$('.suggestions li');
for (const item of suggestions) {
const text = await item.textContent();
if (text.includes('Playwright Tutorial')) {
await item.click();
break;
}
}
Explanation: Loops each suggestion, matches text, and clicks if it contains `”Playwright Tutorial”`.
21. How To Handle Alerts in Playwright
page.once('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept(); // or dialog.dismiss();
});
await page.click('#triggerAlert');
Explanation: Listens for the alert dialog, logs message, and accepts/dismisses.
22. How To Handle Frames and iframes in Playwright
const frame = page.frameLocator('#myFrame');
await frame.fill('#username', 'admin');
await frame.click('#loginBtn');
Explanation: Finds #myFrame
as an iframe, fills & clicks inside it.
23. How To Handle Multiple Tabs in Playwright
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('a[target=_blank]'),
]);
await newPage.waitForLoadState();
await newPage.fill('#email', 'test@example.com');
Explanation: Waits for `’page’` event plus the user click that opens a new tab, then interacts with it.
24. How To Handle Dynamic Network Calls in Playwright
await page.click('#loadDataButton');
await page.waitForLoadState('networkidle');
await expect(page.locator('.result')).toContainText('Data Loaded');
Explanation: Clicks a button that triggers network calls, waits for `networkidle`, then checks `.result` text.
25. How To Read Data from JSON Files (Data-Driven Tests)
data.json
[
{ "username": "user1@example.com", "password": "pass123" },
{ "username": "user2@example.com", "password": "pass456" }
]
Test Example
const testData = require('./data.json');
const { test, expect } = require('@playwright/test');
testData.forEach(({ username, password }) => {
test(`Login test for ${username}`, async ({ page }) => {
await page.goto('https://example.com');
await page.fill('#user', username);
await page.fill('#pass', password);
await page.click('#loginBtn');
await expect(page.locator('.dashboard')).toBeVisible();
});
});
Explanation: Iterates over JSON data, runs test for each user.
26. How To Generate Allure Reports in Playwright (with Screenshots)
Install Allure
npm i -D allure-playwright
Configure playwright.config.js
module.exports = {
reporter: [
['allure-playwright'],
['html']
],
use: {
screenshot: 'only-on-failure',
video: 'retain-on-failure'
}
};
Explanation: Adds Allure + HTML reporters, captures screenshots/videos on failure.
Run & Generate
npx playwright test
npx allure generate allure-results --clean -o allure-report
npx allure open allure-report
Explanation: Runs tests, generates Allure results, opens the report.
27. Page Object Model in Playwright (with JavaScript)
File: loginPage.js
class LoginPage {
constructor(page) {
this.page = page;
this.usernameInput = '#username';
this.passwordInput = '#password';
this.loginBtn = '#loginBtn';
}
async login(username, password) {
await this.page.fill(this.usernameInput, username);
await this.page.fill(this.passwordInput, password);
await this.page.click(this.loginBtn);
}
}
module.exports = LoginPage;
Explanation: Class to manage login elements and actions.
Using POM in a Test
const { test, expect } = require('@playwright/test');
const LoginPage = require('./loginPage');
test('Login with valid credentials', async ({ page }) => {
const loginPage = new LoginPage(page);
await page.goto('https://example.com');
await loginPage.login('admin@example.com', 'admin123');
await expect(page.locator('.dashboard')).toBeVisible();
});
Explanation: Instantiates LoginPage
, calls login()
, checks .dashboard
.
28. How To Push Playwright Tests to GitHub
git init
git add .
git commit -m "first commit"
git remote add origin https://github.com/YourUsername/playwright-demo.git
git push -u origin main
Explanation: Initializes local Git repo, commits code, links to GitHub, and pushes to main
.
29. How To Run Playwright with Jenkins
Prerequisites
- Jenkins installed
- Node.js on same machine/agent
Steps
- New Freestyle Project → Source Code Management (Git) → your repo.
- Under Build:
npm install npx playwright install npx playwright test --project=chromium --headed
- Save & Build.
Explanation: Installs dependencies, ensures browsers, runs tests on Chromium in headed mode.
30. Conclusion
This comprehensive tutorial has walked you through:
- Installing Node & VSCode on Windows/Mac
- Creating your first Playwright test
- Interacting with elements: typing, clicking, verifying text
- Advanced topics: screenshots, videos, trace files, codegen, retries
- Handling dropdowns, mouse hover, file uploads, keyboard, autocomplete, alerts, frames, tabs, dynamic network
- Data-driven tests (JSON), Allure reports, Page Object Model
- GitHub pushes & Jenkins integration
Happy Testing! If you face issues, always re-check logs or refer to the official Playwright docs.
All Assertions, Actions, and Locator Strategies
Below are all the Playwright Assertions, Actions, and Locator strategies you’ll frequently use, with an explanation of each.
A. Assertions
await expect(element).toBeVisible(); // Visible in DOM
await expect(element).toBeHidden(); // In DOM but hidden
await expect(element).toHaveText('Exact'); // Exact text
await expect(element).toContainText('Part'); // Partial text
await expect(element).toHaveAttribute('attr', 'value'); // Specific attribute
await expect(page).toHaveTitle('Page Title'); // Page title check
await expect(page).toHaveURL('https://...'); // URL check
await expect(checkbox).toBeChecked(); // For
await expect(button).toBeEnabled(); // Element is enabled
await expect(button).toBeDisabled(); // Element is disabled
Explanation: expect(...).toBeVisible()
ensures element is displayed, toBeHidden()
ensures it’s in DOM but not displayed, etc.
B. Actions
Playwright “Actions” let you interact with the page—click, type, etc.
- Navigation
await page.goto('https://example.com'); // Opens URL await page.reload(); // Reloads page await page.waitForLoadState('networkidle'); // Waits for no ongoing requests
- Typing & Clicking
await page.fill(selector, text); // Clears & types text await page.type(selector, text); // Types text char by char await page.click(selector); // Clicks an element
- Hover
await page.hover(selector); // Hovers over an element
- Screenshots
await page.screenshot({ path: 'screenshot.png', fullPage: true });
- Videos
Configured inplaywright.config.js
:screenshot: 'on' | 'off' | 'only-on-failure'
video: 'on' | 'off' | 'retain-on-failure'
- Dialogs
page.once('dialog', async dialog => { await dialog.accept(); // or dialog.dismiss(); });
- Keyboard
await page.keyboard.press('Enter'); await page.keyboard.type('Hello');
- Mouse
await page.mouse.move(x, y); await page.mouse.click(x, y);
- Select (Dropdown)
await page.selectOption(selector, valueOrLabelOrIndex);
- File Upload
await page.setInputFiles(selector, filePaths);
- Frames
const frame = page.frameLocator(frameSelector); await frame.click('button');
- Multiple Tabs
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.click('a[target="_blank"]'), ]);
C. Locator Strategies
- CSS Selectors
page.locator('#id'); page.locator('.class'); page.locator('div > span');
- Text
page.getByText('Exact Text');
- Role (ARIA)
page.getByRole('button', { name: 'Sign in' });
- Placeholder
page.getByPlaceholder('Enter your email');
- Label
page.getByLabel('Username');
- Test ID
page.getByTestId('my-test-id');
- XPath
page.locator('//div[@id="main"]');
Explanation: CSS is most common; you can also target text, roles, placeholders, labels, test IDs, or XPath.