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.
As described on its official homepage:
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 |
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.
# Using npm npm init playwright@latest # Using yarn yarn create playwright
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.
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
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/); });
Each test method has:
Key methods include:
Here are common commands:
# Using npm npm init playwright@latest # Using yarn yarn create playwright
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
npx playwright test
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.
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.
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/); });
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
Use locator.selectOption() to interact with
npx playwright test landing-page.spec.ts
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');
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);
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.
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 } });
Use locator.focus() to focus on an element:
# Using npm npm init playwright@latest # Using yarn yarn create playwright
The drag-and-drop process involves four steps:
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
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
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/); });
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.
Cost Efficiency
Developer Experience
Scalability and Performance
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!