Dealing with Long UI Tests in Playwright: Tips and Tricks

Abstract: Resolve slow Playwright UI tests by implementing parallel execution, selective running, and efficient locators.

Created: 2026-08-18 by
Optimizing long UI tests in Playwright requires a strategic combination of parallel execution, selective test running, and efficient locator strategies. By leveraging built-in features like test sharding, retry logic, and video recording controls, you can significantly reduce feedback loops without compromising coverage. This guide details practical steps to streamline your testing pipeline for faster, more reliable results.

Parallel Execution Strategies

One of the most effective ways to handle lengthy UI test suites is to run tests in parallel. Playwright supports running multiple browser contexts simultaneously, which drastically reduces total execution time. You can configure this by modifying your playwright.config.ts file. The workers option determines how many processes run concurrently. Setting this to a value higher than one allows Playwright to distribute tests across available CPU cores. For example, setting workers: 4 will run four tests at the same time. However, be cautious not to overload your machine. If you are running on a CI/CD server, monitor resource usage to ensure stability. Additionally, use the --shard flag when running from the command line to split your test suite across multiple machines or containers. This is particularly useful for large suites that exceed local hardware capabilities.

Selective Test Running

Running only relevant tests during development saves significant time. Instead of executing the entire suite, focus on files or tests that have changed. While tools like VS Code offer extensions for running last touched files, Playwright has native support for filtering. Use the -g or --grep flag to run tests matching a specific pattern. For instance, npx playwright test -g "login" runs only tests containing "login" in their title. You can also mark tests as slow or flaky using the test.slow() method. This helps identify bottlenecks in your suite. Furthermore, consider using tags to categorize tests. Add custom annotations to your test definitions to group them by feature or priority. This allows you to run subsets of tests based on business needs, such as smoke tests before deployment.

Efficient Locator Strategies

Slow tests often stem from inefficient locators. Avoid using CSS selectors that traverse deep DOM trees. Instead, prefer role-based locators like getByRole or text-based locators like getByText. These are more resilient to structural changes and faster to resolve. Playwright’s auto-waiting mechanism handles common actions like clicking and typing, but explicit waits can add unnecessary delays if misused. Remove redundant assertions. Each assertion adds overhead to the test execution. Focus on verifying critical user flows rather than every minor detail. Use expect with appropriate timeouts only when necessary. For dynamic content, rely on Playwright’s built-in retries for network requests and element visibility. This reduces the need for manual polling loops that slow down tests.

Optimize Test Data and Setup

Setting up test data can be a major bottleneck. Use fixtures to manage state efficiently. Define reusable fixtures in your playwright.config.ts or test files to avoid duplicating setup code. For example, create a fixture that logs in a user once per test file, rather than per test case. This reduces authentication overhead significantly. Consider using database seeding for complex scenarios. Instead of relying on API calls to create users, insert records directly into the database. This bypasses application logic and speeds up setup. Ensure that test data is isolated to prevent conflicts between parallel tests. Use unique identifiers for each test run to maintain independence.

CI/CD Integration and Caching

Integrating Playwright with CI/CD pipelines requires careful configuration. Cache node modules and Playwright browsers to speed up subsequent runs. Most CI providers allow caching directories between jobs. Store these caches in a persistent volume to avoid re-downloading dependencies. Additionally, use artifacts to store test reports and videos for failed tests. This aids in debugging without slowing down successful runs. Review the provided article on Troubleshooting VSCode: DebugTest Testing Sidebar for insights into local debugging efficiency, which complements CI optimizations. Similarly, understanding How to Run last Touched Test File in Visual Studio Code with TypeScript and Vitest can help refine your local development workflow, ensuring quick iterations before pushing to CI.

Frequently Asked Questions

How do I enable video recording for all tests?

Set the video option to "on-first-retry" or "on-all-failures" in your config. This ensures videos are only captured when needed, saving disk space and processing time. Avoid setting it to "on" for all tests unless absolutely necessary for debugging.

Can I run tests in headed mode for debugging?

Yes, use the --headed flag when invoking Playwright. This opens the browser window, allowing you to observe test execution step-by-step. It is slower than headless mode but invaluable for identifying visual issues or timing problems.

What causes flaky tests in Playwright?

Flakiness often stems from race conditions or unstable network responses. Use Playwright’s auto-waiting features and avoid hard-coded sleeps. Implement retry logic for assertions and ensure test isolation by resetting state between runs. Analyze failure patterns to identify consistent triggers.

How can I reduce memory usage during parallel execution?

Limit the number of workers to match your available RAM. Close unused browser contexts promptly. Use browser.close() after tests finish. Monitor memory profiles to detect leaks in your test code or third-party libraries.

Is it better to use page objects or inline scripts?

Page object models improve maintainability but add abstraction overhead. For small projects, inline scripts may be faster. Choose based on team size and project complexity. Consistency is key; mix approaches only if necessary for specific components.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More