Getting Started with Playwright Testing

Playwright is a versatile E2E testing framework designed for reliability and performance. Its advanced features make it a preferred choice for modern applications. Here’s how you can begin your Playwright journey.

Environment Setup

To begin using Playwright, ensure you have the following:

  • Node.js: Install the latest version from the Node.js official website.
  • Package Manager: Use NPM or Yarn to manage dependencies.
  • Text Editor/IDE: VS Code with the Playwright extension is recommended for productivity.

 

Setting Up Playwright

1. Install Playwright

npm init playwright@latest

 

2. Choose Browsers to Install:

During setup, select browsers to test (Chromium, Firefox, WebKit).

 

3. Run Playwright Tests:

Use the built-in test runner:

npx playwright test

 

4. Configure Playwright:

Customize testing settings with playwright.config.ts:

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

export default defineConfig({

    testDir: './tests',

    timeout: 30000,

    retries: 2,

    reporter: 'html',

    use: {

        baseURL: 'https://example.com',

        headless: true,

        trace: 'retain-on-failure',

        screenshot: 'only-on-failure',

    },

});

 

5. Advanced Playwright Capabilities

  • Parallel Test Execution: Playwright reduces test suite runtime with parallel execution.
  • API Mocking: Intercept and mock network requests for testing front-end behavior.
  • Visual Comparisons: Use snapshot testing to detect UI regressions.
  • Debugging Tools: Playwright Inspector helps debug flaky tests and pinpoint issues.

 

How Playwright Combines UI and API Testing

Playwright provides powerful APIs to intercept, mock, and validate network requests, all within the context of a UI test. Here’s how you can use these capabilities:


1. Intercepting and Validating API Requests

Playwright can monitor network traffic during a test, allowing you to validate API calls triggered by the UI.

Example
Verifying that a search query sends the correct API request:

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

 

test('Verify search API call from UI', async ({ page }) => {

    await page.route('https://api.example.com/search', route => {

        // Validate the request parameters

        const postData = JSON.parse(route.request().postData() || '{}');

        expect(postData.query).toBe('Playwright');

        route.continue();

    });

 

    // Perform a search action in the UI

    await page.goto('https://example.com');

    await page.fill('#search-box', 'Playwright');

    await page.click('#search-button');

});

 

In this example

  • The page.route() method intercepts API requests.
  • The test validates the request payload before continuing the request.

 

2. Mocking API Responses

Simulate API responses to test the UI’s behavior under different conditions without relying on live APIs.

Example

Mocking a successful login response:

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

 

test('Mock login API response', async ({ page }) => {

    await page.route('https://api.example.com/login', route => {

        route.fulfill({

            status: 200,

            body: JSON.stringify({ token: 'fake-token', user: { name: 'John Doe' } }),

        });

    });

 

    await page.goto('https://example.com/login');

    await page.fill('#username', 'testuser');

    await page.fill('#password', 'password123');

    await page.click('#login-button');

 

    // Validate successful login behavior in the UI

    await expect(page.locator('body')).toContainText('Welcome, John Doe');

});


With mocked responses, you can

  • Test UI behaviors for different API response scenarios (e.g., success, error, timeout).
  • Reduce dependencies on external environments during development.

 

3. Testing API and UI Integration

Playwright allows you to validate end-to-end flows that span both UI interactions and API calls.

Example

Testing a user registration flow

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

test('User registration flow', async ({ page }) => {

    await page.route('https://api.example.com/register', async route => {

        // Capture the registration request

        const requestData = JSON.parse(route.request().postData() || '{}');

        expect(requestData.email).toBe('test@example.com');

       

        // Mock the response

        route.fulfill({

            status: 201,

            body: JSON.stringify({ id: 12345, email: 'test@example.com' }),

        });

    });

 

    // Perform registration steps in the UI

    await page.goto('https://example.com/register');

    await page.fill('#email', 'test@example.com');

    await page.fill('#password', 'password123');

    await page.click('#register-button');

 

    // Validate UI updates after successful registration

    await expect(page.locator('text=Registration successful')).toBeVisible();

});


This approach ensures that

  • The UI sends the correct data to the backend.
  • The backend responses are handled appropriately by the UI.

 

Best Practices for Effective Testing with Playwright

  • Organize Test Suites: Group tests by features for clarity.
  • Reuse Code: Create helper functions for common actions.
  • Minimize Flakiness: Use Playwright’s built-in retries and auto-waiting.
  • Integrate with CI/CD: Run Playwright tests as part of your CI pipeline.

 

Conclusion

Playwright transforms E2E testing by seamlessly integrating UI and API validations. Its speed, reliability, and modern features make it an invaluable tool for building robust applications. With Playwright, developers and QA teams can confidently deliver software that meets and exceeds user expectations.

 

Colleague spothlight 

This blog is live thanks to

Profile Picture Iskra

       Iskra Antonova
        Lead QA Automation

 

 

 

Continue reading

Why End-to-End (E2E) Testing Matters? 

In today's fast-paced software development world, delivering seamless, high-quality user experiences is crucial. However, ensuring quality isn't just about checking individual components - it's about making sure everything works together smoothly. This is where End-to-End (E2E) testing plays a key role.

E2E testing validates the entire user journey by simulating real-world user interactions across the system, serving as the final checkpoint to ensure your application performs as expected.

Leading the Way in Software Development and QA Automation

It is our great pleasure to introduce our colleague Iskra - a Lead QA Automation in Software Development who holds a Ph.D. in Industrial Automation. She has played a key part in the Plan A dream team since March 2023 and has over 15 years of experience in the tech industry.
Iskra excels at developing comprehensive testing strategies, as well as leading and mentoring teams in test automation, and with her enviable expertise and resilient team spirit, she is unmatched in driving projects to success.

Mastering QA Series #2: 9 Steps to enhance your QA strategy

In today's competitive digital landscape, ensuring the quality of your software products is more critical than ever. A robust Quality Assurance (QA) strategy aims to enhance product reliability while also ensuring customer satisfaction and loyalty. To achieve this, integrating QA seamlessly into your development process and continuously improving its effectiveness are of utmost importance.

In this comprehensive guide, we delve into nine essential steps to ensure you have the right QA strategy to support your business goals. Whether you're establishing a new QA process or refining an existing one, these steps will help your team achieve better product quality without compromising efficiency and innovation.

Newsletter

Stay up to date, subscribe to our newsletter !