Playwright: A Guide to Browser Automation & Testing

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

✔ 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!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
how-to-use-tailwind-css-with-the-clamp-function-for-responsive-designs

How to Use Tailwind CSS with the Clamp Function for Responsive Designs

Next Post
understanding-relationships-in-mongodb-and-mongoose

Understanding Relationships in MongoDB and Mongoose

Related Posts