search
HomeWeb Front-endJS TutorialPlaywright: A Comprehensive Overview of Web UI Automation Testing Framework

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

Run the example test case:

npx playwright test

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

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/);
});
  • 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
  • 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
  • Debug a test case:
npx playwright test

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

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 ,

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/);
});

Checkbox and Radio

Use locator.setChecked() or locator.check() to interact with input[type=checkbox], input[type=radio], or elements with the [role=checkbox] attribute:

  npx playwright test

Select Control

Use locator.selectOption() to interact with

  npx playwright test landing-page.spec.ts

Mouse Clicks

Basic operations:

  npx playwright test --debug

For elements covered by others, use force click:

npx playwright codegen https://leapcell.io/

Or trigger the click event programmatically:

// Text input
await page.getByRole('textbox').fill('Peter');

Typing Characters

The locator.type() method simulates typing character-by-character, triggering keydown, keyup, and keypress events:

await page.getByLabel('I agree to the terms above').check();

expect(await page.getByLabel('Subscribe to newsletter').isChecked()).toBeTruthy();

// Uncheck
await page.getByLabel('XL').setChecked(false);

Special Keys

Use locator.press() for special keys:

// Select by value
await page.getByLabel('Choose a color').selectOption('blue');

// Select by label
await page.getByLabel('Choose a color').selectOption({ label: 'Blue' });

// Multi-select
await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue']);

Supported keys include Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, F1-F12, Digit0-Digit9, and KeyA-KeyZ.

File Upload

Use locator.setInputFiles() to specify files for upload. Multiple files are supported:

// Left click
await page.getByRole('button').click();

// Double click
await page.getByText('Item').dblclick();

// Right click
await page.getByText('Item').click({ button: 'right' });

// Shift+click
await page.getByText('Item').click({ modifiers: ['Shift'] });

// Hover
await page.getByText('Item').hover();

// Click at specific position
await page.getByText('Item').click({ position: { x: 0, y: 0 } });

Focus Element

Use locator.focus() to focus on an element:

   # Using npm
   npm init playwright@latest

   # Using yarn
   yarn create playwright

Drag and Drop

The drag-and-drop process involves four steps:

  1. Hover the mouse over the draggable element.
  2. Press the left mouse button.
  3. Move the mouse to the target position.
  4. Release the left mouse button.

You can use the locator.dragTo() method:

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

Alternatively, manually implement the process:

npx playwright test

Dialog Handling

By default, Playwright automatically cancels dialogs like alert, confirm, and prompt. You can pre-register a dialog handler to accept dialogs:

Running 6 tests using 6 workers

  6 passed (10s)

To open the last HTML report run:

  npx playwright show-report

Handling New Pages

When a new page pops up, you can use the popup event to handle it:

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/);
});

The Best Platform for Playwright: Leapcell

Playwright: A Comprehensive Overview of Web UI Automation Testing Framework

Leapcell is a modern cloud computing platform designed for distributed applications. It adopts a pay-as-you-go model with no idle costs, ensuring you only pay for the resources you use.

Unique Benefits of Leapcell for Playwright Applications

  1. Cost Efficiency

    • Pay-as-you-go: Avoid resource waste during low traffic and scale up automatically during peak times.
    • Real-world example: For example, on getdeploying.com’s calculations, renting a 1 vCPU and 2 GB RAM virtual machine in traditional cloud services costs around $25 per month. On Leapcell, $25 can support a service handling 6.94 million requests with an average response time of 60 ms, giving you better value for money.
  2. Developer Experience

    • Ease of use: Intuitive interface with minimal setup requirements.
    • Automation: Simplifies development, testing, and deployment.
    • Seamless integration: Supports Go, Python, Node.js, Rust, and more.
  3. Scalability and Performance

    • Auto-scaling: Dynamically adjusts resources to maintain optimal performance.
    • Asynchronous optimization: Handles high-concurrency tasks with ease.
    • Global reach: Low-latency access supported by distributed data centers.

For more deployment examples, refer to the documentation.

The above is the detailed content of Playwright: A Comprehensive Overview of Web UI Automation Testing Framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function