π Let's Connect! Follow me on GitHub for new projects.
Introduction
Playwright is a browser automation library designed for fast, reliable, and cross-browser testing. It supports Chromium, Firefox, and WebKit, making it a powerful tool for developers looking to automate web interactions, test applications, and improve UI reliability.
This guide will cover:
β
Installing and setting up Playwright
β
Writing and running tests
β
Handling authentication
β
Network mocking
β
Advanced debugging techniques
1. What is Playwright?
Playwright is a Node.js library for browser automation. It allows you to control browsers, interact with elements, take screenshots, record videos, and perform UI tests.
Key Features
β Supports Chromium, Firefox, and WebKit
β Works on Windows, macOS, and Linux
β Headless mode for fast execution
β Built-in network interception & API testing
β Mobile emulation & geolocation testing
2. Installing Playwright
Playwright requires Node.js 14 or later.
Installation via NPM
npm init playwright@latest
β This command sets up Playwright with browsers, testing framework, and examples.
Installing Playwright Manually
npm install @playwright/test
npx playwright install
β Installs Chromium, Firefox, and WebKit.
3. Writing & Running a Basic Test
Letβs create a basic Playwright test to check if a webpage loads correctly.
Example: Opening a Webpage
Create a file example.test.js
:
const { test, expect } = require('@playwright/test');
test('Check website title', async ({ page }) => {
await page.goto('https://example.com');
const title = await page.title();
expect(title).toBe('Example Domain');
});
Running the Test
npx playwright test
β Playwright automatically runs tests in headless mode.
β Add --headed
to see the browser UI.
4. Handling Authentication in Playwright
Many web applications require authentication before accessing protected areas. Playwright makes it easy to store and reuse authentication sessions.
Example: Persistent Login
test('Login and save session', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com/login');
await page.fill('input[name="username"]', 'testuser');
await page.fill('input[name="password"]', 'password123');
await page.click('button[type="submit"]');
// Save authentication state
await context.storageState({ path: 'auth.json' });
});
β This stores authentication in auth.json
, allowing future tests to reuse the session.
Using the Saved Session in Other Tests
test.use({ storageState: 'auth.json' });
test('Visit dashboard as authenticated user', async ({ page }) => {
await page.goto('https://example.com/dashboard');
await expect(page).toHaveText('Welcome, testuser');
});
β This prevents the need to log in every test run, making tests faster.
5. Network Interception & Mocking
Playwright allows mocking API responses, making tests independent from actual server data.
Mocking API Responses
test('Mock API response', async ({ page }) => {
await page.route('https://api.example.com/user', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 1, name: 'Mock User' }),
});
});
await page.goto('https://example.com/profile');
await expect(page.locator('.username')).toHaveText('Mock User');
});
β Ensures tests run even if the backend is down.
β Useful for testing edge cases and error handling.
6. Taking Screenshots & Recording Videos
Playwright supports automated screenshots and video recordings for debugging.
Taking a Screenshot
await page.screenshot({ path: 'screenshot.png' });
Recording a Video
To enable video recording, add this to your playwright.config.js
:
use: {
video: 'on'
}
β Videos are stored in the test results folder.
7. Running Tests in Parallel
Playwright can run tests concurrently for faster execution.
Enable Parallel Execution
Modify playwright.config.js
:
module.exports = {
use: {
headless: true
},
workers: 4 // Runs tests in 4 parallel processes
};
β Playwright automatically distributes tests across multiple browser instances.
8. Mobile & Geolocation Testing
Playwright supports device emulation for mobile browsers.
Simulating an iPhone
const { devices } = require('@playwright/test');
test.use({ ...devices['iPhone 12'] });
test('Mobile test', async ({ page }) => {
await page.goto('https://example.com');
await page.screenshot({ path: 'mobile.png' });
});
β devices['iPhone 12']
emulates an iPhone screen size and user agent.
Testing Geolocation (GPS)
test('Test location', async ({ page, context }) => {
await context.grantPermissions(['geolocation']);
await page.setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); // San Francisco
});
β Simulates user location for geo-based apps.
9. API Testing with Playwright
Playwright can test API endpoints directly.
Example: Testing a REST API
test('API test', async ({ request }) => {
const response = await request.get('https://jsonplaceholder.typicode.com/posts/1');
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.id).toBe(1);
});
β request.get()
fetches API data.
β expect(response.status()).toBe(200)
ensures success.
10. Debugging in Playwright
If a test fails, debugging helps find the issue.
Using playwright.inspect()
await playwright.inspect();
β Opens Playwright Inspector to pause test execution.
Running in Headed Mode
npx playwright test --headed
β Opens a visible browser window.
Using slowMo
for Slower Execution
const { chromium } = require('playwright');
const browser = await chromium.launch({ headless: false, slowMo: 1000 });
β Slows down interactions for better debugging.
11. Running Playwright Tests in CI/CD
Playwright works with GitHub Actions, Jenkins, and CircleCI.
GitHub Actions Example
Create .github/workflows/playwright.yml
:
name: Playwright Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v2
- name: Install Dependencies
run: npm install
- name: Install Browsers
run: npx playwright install
- name: Run Tests
run: npx playwright test
β Runs tests on every push to GitHub.
Conclusion
Playwright provides a comprehensive feature set for browser automation, testing, and debugging. Whether you're testing UI components, API responses, or mobile layouts, Playwright simplifies automation with a robust API.
π Next Steps:
β
Try Playwright in your project!
β
Experiment with authentication & network mocking.
TLDR β Highlights for Skimmers
- Playwright automates browsers (Chromium, Firefox, WebKit).
- Supports UI testing, API testing, mobile emulation, and geolocation.
- Run tests in parallel with multiple workers for speed.
- Take screenshots & record videos for debugging.
- Use network mocking to test APIs without real server calls.
- Handles authentication using saved sessions.
- Integrates with CI/CD for automated testing.
π¬ Have you used Playwright? Share your experience in the comments!
Top comments (1)
Have you tried Playwright for UI automation yet?
Letβs chat!