Home > Web Front-end > JS Tutorial > Playwright: A Comprehensive Overview of Web UI Automation Testing Framework

Playwright: A Comprehensive Overview of Web UI Automation Testing Framework

Susan Sarandon
Release: 2024-12-26 17:57:09
Original
839 people have browsed it

PlayWright is a Web UI automation testing framework developed by Microsoft.

It aims to provide a cross-platform, cross-language, cross-browser automation testing framework that also supports mobile browsers.

Playwright: A Comprehensive Overview of Web UI Automation Testing Framework

As described on its official homepage:

  • Automatic waiting, intelligent assertions for page elements, and execution tracing make it highly effective in handling the instability of web pages.
  • It controls browsers in a process different from the one running the test, eliminating the limitations of in-process test runners and supporting Shadow DOM penetration.
  • PlayWright creates a browser context for each test. A browser context is equivalent to a brand-new browser profile, enabling zero-cost full test isolation. Creating a new browser context takes just a few milliseconds.
  • Provides features like code generation, step-by-step debugging, and trace viewer.

PlayWright vs. Selenium vs. Cypress

What are the best Web UI automation testing frameworks available today? The standout options include the decade-old Selenium, the recently popular Cypress, and the one we’re introducing here—PlayWright. How do they differ? Below is a summarized comparison for your reference

Feature PlayWright Selenium Cypress
Supported Languages JavaScript, Java, C#, Python JavaScript, Java, C#, Python, Ruby JavaScript/TypeScript
Supported Browsers Chrome, Edge, Firefox, Safari Chrome, Edge, Firefox, Safari, IE Chrome, Edge, Firefox, Safari
Testing Framework Frameworks for supported languages Frameworks for supported languages Frameworks for supported languages
Usability Easy to use and configure Complex setup with a learning curve Easy to use and configure
Code Complexity Simple Moderate Simple
DOM Manipulation Simple Moderate Simple
Community Maturity Improving gradually Highly mature Fairly mature
Headless Mode Support Yes Yes Yes
Concurrency Support Supported Supported Depends on CI/CD tools
iframe Support Supported Supported Supported via plugins
Driver Not required Requires a browser-specific driver Not required
Multi-Tab Operations Supported Not supported Supported
Drag and Drop Supported Supported Supported
Built-in Reporting Yes No Yes
Cross-Origin Support Supported Supported Supported
Built-in Debugging Yes No Yes
Automatic Wait Yes No Yes
Built-in Screenshot/Video Yes No video recording Yes

Key Comparisons:

  • Supported Languages: PlayWright and Selenium support Java, C#, and Python, making them more popular among test engineers who may not be familiar with JavaScript/TypeScript.
  • Technical Approach: Both PlayWright and Selenium use Google’s Remote Debugging Protocol to control Chromium-based browsers. For browsers like Firefox, without such protocols, they use JavaScript injection. Selenium encapsulates this in a Driver, while PlayWright directly calls it. Cypress, on the other hand, uses JavaScript to control browsers.
  • Browser Support: Selenium supports Internet Explorer, which is irrelevant as IE is being phased out.
  • Ease of Use: All three frameworks have a learning curve. However, PlayWright and Cypress are more user-friendly for simple scenarios compared to Selenium.

Getting Started

Although PlayWright supports multiple languages, it heavily relies on Node.js. Regardless of whether you use the Python or Java version, PlayWright requires a Node.js environment during initialization, downloading a Node.js driver. Hence, we’ll focus on JavaScript/TypeScript for this guide.

Installation and Demo

  1. Ensure Node.js is installed.
  2. Initialize a PlayWright project using npm or yarn:
   # Using npm
   npm init playwright@latest

   # Using yarn
   yarn create playwright
Copy after login
Copy after login
Copy after login
  1. Follow the prompts:
    • Choose TypeScript or JavaScript (default: TypeScript).
    • Specify the test directory name.
    • Decide whether to install PlayWright-supported browsers (default: True).

If you choose to download browsers, PlayWright will download Chromium, Firefox, and WebKit, which may take some time. This process occurs only during the first setup unless the PlayWright version is updated.

Project Structure

After initialization, you’ll get a project template:

playwright.config.ts    # PlayWright configuration file
package.json            # Node.js configuration file
package-lock.json       # Node.js dependency lock file
tests/                  # Your test directory
  example.spec.ts       # Template test case
tests-examples/         # Example tests directory
  demo-todo-app.spec.ts # Example test case
Copy after login
Copy after login
Copy after login

Run the example test case:

npx playwright test
Copy after login
Copy after login
Copy after login

The tests execute silently (in headless mode), and results are displayed as:

Running 6 tests using 6 workers

  6 passed (10s)

To open the last HTML report run:

  npx playwright show-report
Copy after login
Copy after login
Copy after login

Example Source Code

Here’s the example.spec.ts test case:

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

test('has title', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  await expect(page).toHaveTitle(/Playwright/);
});

test('get started link', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  await page.getByRole('link', { name: 'Get started' }).click();
  await expect(page).toHaveURL(/.*intro/);
});
Copy after login
Copy after login
Copy after login
  • First Test: Verifies the page title contains "Playwright".
  • Second Test: Clicks the "Get started" link and verifies the URL.

Each test method has:

  • A test name (e.g., 'has title').
  • A function to execute the test logic.

Key methods include:

  • page.goto: Navigates to a URL.
  • expect(page).toHaveTitle: Asserts the page title.
  • page.getByRole: Locates an element by its role.
  • await: Waits for asynchronous operations to complete.

Running Tests from the Command Line

Here are common commands:

  • Run all tests:
   # Using npm
   npm init playwright@latest

   # Using yarn
   yarn create playwright
Copy after login
Copy after login
Copy after login
  • Run a specific test file:
playwright.config.ts    # PlayWright configuration file
package.json            # Node.js configuration file
package-lock.json       # Node.js dependency lock file
tests/                  # Your test directory
  example.spec.ts       # Template test case
tests-examples/         # Example tests directory
  demo-todo-app.spec.ts # Example test case
Copy after login
Copy after login
Copy after login
  • Debug a test case:
npx playwright test
Copy after login
Copy after login
Copy after login

Code Recording

Use the codegen feature to record interactions:

Running 6 tests using 6 workers

  6 passed (10s)

To open the last HTML report run:

  npx playwright show-report
Copy after login
Copy after login
Copy after login

Recorded code can be copied into your files. Note: The recorder might not handle complex actions like hovering.


In-Depth Playwright Guide

Actions and Behaviors

This section introduces some typical Playwright actions for interacting with page elements. Note that the locator object introduced earlier does not actually locate the element on the page during its creation. Even if the element doesn't exist on the page, using the element locator methods to get a locator object won't throw any exceptions. The actual element lookup happens only during the interaction. This differs from Selenium's findElement method, which directly searches for the element on the page and throws an exception if the element isn't found.

Text Input

Use the fill method for text input, mainly targeting ,