Playwright Automation Testing Notes
1. Introduction to Automation Testing
What is Automation Testing?
Automation testing uses tools and scripts to execute test cases. Unlike manual testing, where a
person interacts with the software, automation testing relies on predefined instructions to
perform the same actions. This saves time, ensures consistency, and is especially useful for
repetitive or complex scenarios.
Why Playwright?
Playwright is a modern end-to-end testing tool that stands out for its features:
● Multi-Browser Support: It can run tests on Chromium (Google Chrome/Edge), Firefox,
and WebKit (Safari).
● Fast and Reliable: Built-in auto-wait ensures actions are performed only when the
application is ready.
● Cross-Platform: Playwright tests can be executed on Windows, macOS, and Linux.
● Modern Features: Includes API mocking, mobile device emulation, and more, making it
suitable for testing modern web applications.
2. Setting Up Playwright
Prerequisites
● Node.js: Playwright requires Node.js to run. Install it from the official Node.js website.
● Basic Knowledge of JavaScript/TypeScript: Familiarity with these programming
languages is essential.
Installation Steps
Initialize a Node.js Project: This creates a package.json file to manage dependencies.
npm init -y
1.
Install Playwright: This downloads the Playwright library and necessary browser binaries.
npm install @playwright/test
2.
Run the Test Generator: Playwright provides a code generator to create test scripts
interactively.
npx playwright codegen
3.
Project Structure
A typical Playwright project looks like this:
project-folder/
|-- tests/
| |-- example.test.js # Contains test scripts
|-- playwright.config.js # Global configurations
|-- package.json # Dependency manager
|-- node_modules/ # Installed modules
3. Playwright Basics
Key Concepts
1. Browser: Represents the browser application (e.g., Chrome, Firefox). It launches and
manages browser instances.
2. Context: An isolated environment within a browser. Each context has its own cookies,
cache, and session storage, making it useful for testing independent sessions.
3. Page: Represents a single tab or window in a browser. Most user interactions are
performed on a Page.
Writing a Basic Script
This script navigates to a website and verifies its title:
const { test, expect } = require('@playwright/test');
test('basic test', async ({ page }) => {
await page.goto('https://example.com'); // Navigate to URL
await expect(page).toHaveTitle('Example Domain'); // Check title
});
● page.goto: Navigates to the specified URL.
● expect: Performs assertions, such as verifying the page title.
4. Playwright APIs and Core Concepts
Selectors
Selectors identify elements on the page. Playwright provides several types:
● CSS Selectors: Locate elements by class, ID, or attributes (e.g., .class, #id,
[name="value"]).
● Text Selectors: Match elements containing specific text (e.g., text='Example').
● Custom Selectors: Use locator for more advanced targeting (e.g.,
page.locator('css=selector')).
Actions
Actions simulate user interactions:
Click:
await page.click('button#submit');
●
Type:
await page.type('input#username', 'TestUser');
●
Hover:
await page.hover('div#menu');
●
Assertions
Assertions verify expected outcomes:
Page Title:
await expect(page).toHaveTitle('Page Title');
●
Text Content:
await expect(page.locator('h1')).toHaveText('Welcome');
●
Visibility:
await expect(page.locator('button#login')).toBeVisible();
●
5. Advanced Playwright Features
Emulation
Emulate mobile devices and user environments for responsive testing:
await browser.newContext({
viewport: { width: 375, height: 812 },
userAgent: 'Mobile User Agent'
});
Network Interception
Intercept and mock API responses:
await page.route('**/api/data', route => {
route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ key: 'mocked value' })
});
});
Handling Pop-ups
Dialog Boxes: Handle alert, confirm, or prompt dialogs.
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept();
});
●
Iframes: Interact with content inside iframes.
const frame = page.frame({ name: 'frame-name' });
await frame.click('button');
●
6. Test Automation Framework Design
Page Object Model (POM)
A design pattern that separates locators and test logic:
● Advantages:
○ Reusability: Shared code between tests.
○ Maintainability: Centralized element updates.
Example Implementation:
class LoginPage {
constructor(page) {
this.page = page;
this.usernameInput = page.locator('#username');
this.passwordInput = page.locator('#password');
this.loginButton = page.locator('#login');
}
async login(username, password) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
}
module.exports = LoginPage;
7. Playwright Test Runner
Configuring Playwright
Global settings are defined in playwright.config.js:
module.exports = {
timeout: 30000, // Test timeout
retries: 2, // Retry on failure
use: {
headless: true, // Run tests in headless mode
baseURL: 'https://example.com',
},
};
Parallel Execution
Execute multiple tests simultaneously:
npx playwright test --workers=4
8. Cross-Browser and Parallel Testing
Running on Multiple Browsers
Specify browsers in the configuration:
npx playwright test --project=chromium --project=firefox --project=webkit
Cloud Testing
Playwright integrates with services like BrowserStack or LambdaTest for cloud-based browser
testing. Update configurations accordingly.
9. Debugging and Reporting
Debugging Tools
Playwright Inspector: Visual tool for debugging.
npx playwright test --debug
●
Tracing: Record and replay test execution.
await context.tracing.start({ screenshots: true, snapshots: true });
await context.tracing.stop({ path: 'trace.zip' });
●
Reports
Generate and view HTML reports:
npx playwright show-report
10. CI/CD Integration
Jenkins Integration
Run Playwright tests in a Jenkins pipeline:
npx playwright test
GitHub Actions
Automate Playwright tests with GitHub Actions:
name: Playwright Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
- run: npm install
- run: npx playwright install
- run: npx playwright test
11. Best Practices
● Use Explicit Locators: Avoid ambiguous selectors for better test stability.
● Keep Tests Independent: Ensure tests can run in isolation without dependencies.
● Avoid Hard Waits: Use Playwright’s auto-wait and expect conditions.
● Update Dependencies Regularly: Ensure compatibility with the latest features.
This detailed guide ensures a deep understanding of Playwright automation, with clear
explanations for all terms and concepts to prepare for industry-level challenges.