DEV Community

Cover image for Advanced Playwright Features: Beyond the Basics
Aswani Kumar
Aswani Kumar

Posted on

Advanced Playwright Features: Beyond the Basics

Introduction

Playwright is well-known for its simplicity and efficiency in automating end-to-end tests. While the basics of Playwright can get you started quickly, its advanced features unlock unparalleled capabilities for complex scenarios. In this post, we'll explore some of Playwright's more advanced features and how you can leverage them to build robust and flexible testing frameworks.

1. Network Interception and Mocking

One of Playwright's standout features is its ability to intercept and mock network requests. This allows you to simulate backend responses without depending on the actual API.

Example: Mocking an API response

import { test, expect } from '@playwright/test';

test('mock API response', async ({ page }) => {
  await page.route('https://api.example.com/data', route => {
    route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ key: 'mocked value' }),
    });
  });

  await page.goto('https://your-app-url.com');
  const data = await page.locator('#data').textContent();
  expect(data).toBe('mocked value');
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Testing UI behavior for different API states (success, failure, slow responses).
  • Isolating front-end tests from backend dependencies.

2. Mobile and Device Emulation

Playwright supports device emulation, making it easy to test responsive designs and mobile-specific features.

Example: Emulating an iPhone 12

import { devices } from '@playwright/test';

const iPhone12 = devices['iPhone 12'];

test.use({
  ...iPhone12,
});

test('responsive design test', async ({ page }) => {
  await page.goto('https://your-app-url.com');
  const isMobileMenuVisible = await page.locator('#mobile-menu').isVisible();
  expect(isMobileMenuVisible).toBe(true);
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Testing mobile layouts and touch interactions.
  • Validating browser-specific behaviors.

3. Handling Authentication

Many modern applications require authentication for most functionalities. Playwright provides tools to handle authentication efficiently, such as preserving login sessions or programmatically logging in.

Example: Reusing authenticated sessions

import { test } from '@playwright/test';

let authState;

test.beforeAll(async ({ browser }) => {
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://your-app-url.com/login');
  await page.fill('#username', 'user');
  await page.fill('#password', 'pass');
  await page.click('#login-button');
  await page.context().storageState({ path: 'auth.json' });
  authState = page.context().storageState();
});

test.use({ storageState: authState });

test('authenticated test', async ({ page }) => {
  await page.goto('https://your-app-url.com/dashboard');
  const welcomeMessage = await page.locator('#welcome').textContent();
  expect(welcomeMessage).toContain('Welcome');
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Running tests that require logged-in states.
  • Speeding up tests by skipping repetitive login steps.

4. Visual Regression Testing

Playwright can capture screenshots and compare them for visual regression testing.

Example: Comparing screenshots

import { test, expect } from '@playwright/test';

test('visual regression test', async ({ page }) => {
  await page.goto('https://your-app-url.com');
  const screenshot = await page.screenshot();
  expect(screenshot).toMatchSnapshot('homepage.png');
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Detecting unintended UI changes.
  • Validating visual consistency across different releases.

5. Parallel Test Execution

Playwright’s parallel test execution can significantly reduce test run times by running tests concurrently.

Configuration: Adjusting workers

In your playwright.config.ts:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  workers: 4, // Number of parallel workers
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Speeding up test suites.
  • Optimizing CI/CD pipelines.

6. Custom Test Fixtures

Playwright allows you to create custom fixtures to set up reusable test utilities.

Example: Custom database fixture

import { test as base } from '@playwright/test';

const test = base.extend({
  db: async ({}, use) => {
    const db = new DatabaseConnection();
    await db.connect();
    await use(db);
    await db.disconnect();
  },
});

test('test with database', async ({ db, page }) => {
  const data = await db.query('SELECT * FROM users');
  expect(data).not.toBeNull();
});
Enter fullscreen mode Exit fullscreen mode

7. Continuous Integration and Reporting

Integrating Playwright with CI tools (e.g., GitHub Actions, GitLab CI) ensures tests run automatically on code changes. Playwright’s built-in reporters make it easy to analyze test results.

Example: HTML Reporter

In playwright.config.ts:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: [['html', { outputFolder: 'test-results' }]],
});
Enter fullscreen mode Exit fullscreen mode

Key Use Cases:

  • Automating test execution on CI platforms.
  • Generating detailed test reports for debugging and analysis.

Conclusion

Mastering Playwright’s advanced features will empower you to handle complex testing scenarios with ease. Whether it’s mocking APIs, handling authentication, or running tests in parallel, Playwright has tools for every challenge.

Which advanced feature do you find most intriguing? Share your thoughts or questions in the comments below!

Top comments (0)