


Playwright: A Comprehensive Overview of Web UI Automation Testing Framework
Dec 26, 2024 pm 05:57 PMPlayWright 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.
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
- Ensure Node.js is installed.
- Initialize a PlayWright project using npm or yarn:
# Using npm npm init playwright@latest # Using yarn yarn create playwright
- 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:
- Hover the mouse over the draggable element.
- Press the left mouse button.
- Move the mouse to the target position.
- 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
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
-
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.
-
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.
-
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)
