DEV Community

Cover image for Playwright: A Guide to Browser Automation & Testing
Austin W
Austin W

Posted on

Playwright: A Guide to Browser Automation & Testing

πŸ‘‹ 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
Enter fullscreen mode Exit fullscreen mode

βœ” This command sets up Playwright with browsers, testing framework, and examples.

Installing Playwright Manually

npm install @playwright/test
npx playwright install
Enter fullscreen mode Exit fullscreen mode

βœ” 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');
});
Enter fullscreen mode Exit fullscreen mode

Running the Test

npx playwright test
Enter fullscreen mode Exit fullscreen mode

βœ” 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' });
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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');
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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');
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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' });
Enter fullscreen mode Exit fullscreen mode

Recording a Video

To enable video recording, add this to your playwright.config.js:

use: {
    video: 'on'
}
Enter fullscreen mode Exit fullscreen mode

βœ” 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
};
Enter fullscreen mode Exit fullscreen mode

βœ” 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' });
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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);
});
Enter fullscreen mode Exit fullscreen mode

βœ” 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();
Enter fullscreen mode Exit fullscreen mode

βœ” Opens Playwright Inspector to pause test execution.

Running in Headed Mode

npx playwright test --headed
Enter fullscreen mode Exit fullscreen mode

βœ” Opens a visible browser window.

Using slowMo for Slower Execution

const { chromium } = require('playwright');
const browser = await chromium.launch({ headless: false, slowMo: 1000 });
Enter fullscreen mode Exit fullscreen mode

βœ” 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
Enter fullscreen mode Exit fullscreen mode

βœ” 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)

Collapse
 
austinwdigital profile image
Austin W

Have you tried Playwright for UI automation yet?

  • If so, what’s your favorite feature?
  • If not, what’s stopping you from giving it a try?

Let’s chat!