Understanding Different Types of Playwright Waits

Discover the different types of Playwright Wait commands and how to use them. For accurate results, run your Playwright tests on BrowserStack.

Get Started free
Home Guide Understanding Different Types of Playwright Wait

Understanding Different Types of Playwright Wait

By Yogendra Porwal , Community Contributor -

One of the most important concepts you’ll encounter when working with test automation is waiting for elements or events to happen. Waiting might sound simple, but handling wait conditions efficiently is crucial for stable and reliable test execution.

Playwright is a popular end-to-end testing framework that simplifies this with robust wait mechanisms that help manage dynamic content.

This article dives into the different types of Playwright waits and how to use them effectively.

What is Playwright Wait?

Playwright Wait refers to the mechanisms that pause the script execution until certain conditions in the browser are met; such as elements becoming visible or network responses being completed.

These waits are integral to synchronizing tests with the dynamic nature of web applications.

Importance of Playwright Wait

Here are the reasons that signify the importance of Playwright Wait in testing:

  • If your website has transitions or animations, Playwright wait ensures that these actions are done, before executing the tests, thereby reducing the opportunity of errors.
  • There is an unpredictability or flakiness associated with tests where the actions occur before the elements are fully loaded or visible. Playwright automatically waits for elements to be ready, which helps the tests run reliably. Thus preventing flaky tests.
  • Before performing any action, like clicking a button, entering details in a form etc, it’s important to wait until that element is available in the DOM. This prevents errors that occur when trying to interact with non-existent or hidden elements.
  • Playwright offers high customizability by providing wait options like waitForSelector, waitForNavigation, and waitForTimeout to fit different testing requirements.
  • Playwright Wait improves test accuracy and reliability of results since actions are performed at the right time.

When to Use Playwright Wait

You should use Playwright Wait whenever

  • There is a need to pause script execution
  • Until the DOM is ready
  • A specific element becomes visible (Example: Animations)
  • Any network requests or page navigations are complete.

This helps avoid timing issues where the script continues running before the web page is fully ready.

Understanding Auto-Waiting in Playwright

Playwright has built-in auto-waiting, meaning actions like clicking or typing automatically wait for the target element to be ready. This reduces the need for manual waits and simplifies the code, making tests more efficient.

For example, a click action in Playwright automatically waits for the following conditions to be met:

  • The locator can uniquely identify only one element
  • The Element is visible
  • The Element is stable,
  • The element can receive Events (as in not behind any other elements)
  • The element is Enabled

Exploring Different Types of Waits in Playwright [with Examples]

Here are different types of Playwright waits along with their examples

1. page.waitForTimeout()

This is the simplest wait function, which pauses the execution for a specified time (in milliseconds). It’s generally discouraged as it introduces fixed delays and can make tests slower.

The below javascript example will add a hard wait of 3 sec.

await page.waitForTimeout(3000); // Waits for 3 seconds

2. page.waitForSelector()

It enables scripts to wait for an element with a matching selector to be visible. This is a preferred method for waiting, as it ensures that the test only proceeds once the required element is ready.

You can use this example to let your code wait till the submit button is not visible.

await page.waitForSelector('#submit-button');

It also accepts an optional parameter state, that provides more granular control over over the element’s specific state, like waiting until the element disappears or is not part of DOM. By default ,the value for the state parameter is set to visible.

Here is an example to let your code wait until the submit button disappears from the page:

await page.waitForSelector('#submit-button', 'hidden');

3. page.waitForNavigation()

This wait ensures that the script pauses until page navigation is complete. It’s useful when testing page transitions, redirects, or any other action that triggers navigation.

Example;

await page.waitForNavigation();

This method from Playwright is really helpful when tests involve navigation after an unspecified timeout.

Have a look at the code for more clarity.

await page.goto('https://www.bstackdemo.com/');

const waitPromise = page.waitForNavigation();

await page.locator('#orders').click();

await waitPromise;

4. page.waitForRequest()

This wait pauses the test until a specific network request is triggered.

Take the example of placing an order. There would be some calculations involved before the orders are submitted to the backend.

When that’s the case, the code below can halt execution until the ‘checkoutrequest is triggered.

await page.waitForRequest(request => request.url() === 'https://www.bstackdemo.com/api/checkout');

5. page.waitForResponse()

This wait is similar to the previous one; the only difference is that it waits until a specific network response is returned.

It is useful for waiting on API responses or other server communications.

It can be used in two ways: Wait for a matched response from a network request with the predicate and Wait for a complete URL to have a response.

Wait for a matched response from a network request with the predicate:

The below example will wait till the API request for ‘/orders’ is completed successfully.

await page.waitForResponse(response =>

   response.url().includes('api/orders')

   && response.status() === 200

   && response.request().method() === 'GET'

 );

Wait for a complete URL to have a response:

This example will also wait for ‘/orders’ api to have a response but in a shorter way.

page.waitForResponse('https://www.bstackdemo.com/api/orders');

6. page.waitForLoadState()

Waits for the page to reach a specific load state such as “load,” “domcontentloaded,” or “networkidle.” This is helpful for ensuring that the page is fully loaded before interacting with elements.

For example, the below code will wait till all the network requests are fulfilled with no new ones to be triggered:

await page.waitForLoadState('networkidle');

How to Run Your Playwright Test on BrowserStack Automate

Here’s a step-by-step process to run your Playwright Test on BrowserStack Automate to facilitate effective results:

Prerequisites

  • A test automation suite using Playwright. You can use node-js-playwright-browserstack
  • Node v14+ is installed on your machine.

This guide uses Java script in all code snippets and demos. You can choose any language/framework of your choice with BrowserStack (Java, C#, Python, etc.)

Step By Step Guide to Running Playwright Tests

Running Playwright tests on real devices via BrowserStack Automate allows for comprehensive cross-browser testing on real user conditions.

The easiest way to get started is with BrowserStack SDK for the Playwright grid:

Step 1. Sign up on BrowserStack

Step 2. Select ‘Accounts & Profile

BrowserStack Dashboards Accounts Profile Section

Step 3. Select ‘Overview’ under ‘Accounts & Profile

Step 4. Under ‘Overview’, Click ‘My Profile’ on the left-side panel

Step 5. Note down your Username and Access key

Username and Access Key for BrowserStack Automate

Step 6. Run the below command to install BrowserStack NodeJS SDK and set up your username and access key.

npm i -D browserstack-node-sdk@latest
npx setup --username "<your-username>" --key "<your-access-key>"

Step 7. The command will create browserstack.yml, containing all the configurations required to run the test on BrowserStack.

Configuration to Run Tests on BrowserStack

Step 8. Run the command below to start the execution of the tests.

npx browserstack-node-sdk playwright test --config =./playwright.config.ts

Step 9. Visit Automate’s dashboard for a comprehensive report on a test suite that offers a detailed overview of results.

BrowserStack Automate Dashboard

Step 10. Use BrowserStack Automate to execute your Playwright tests across different browsers and devices, ensuring compatibility. This can be done by providing platform/device and browser details in browserstack.yml.

How to Avoid Hard Waits in Playwright

Many times, hard waits are added to the scripts to make the test work as expected. However, they use fixed timeouts or waitForTimeout(),which can lead to flaky tests, making them slow and unreliable.

Challenges Brought by Hard Waits

Hard waits—like page.waitForTimeout()—force the test to wait for a set period, regardless of whether the condition has been met. This can cause several problems:

  • Unnecessary Delays: If the required condition is met sooner than the timeout, your test will still waste time waiting.
  • Flaky Tests: Hard waits don’t adapt to the actual state of the app, making tests fragile. If the condition takes longer than expected, the test might fail unpredictably.
    In dynamic applications, this becomes problematic because the test execution can be either too fast or too slow, leading to inconsistent results.

How to Avoid Hard Waits

To avoid hard waits, Playwright provides smarter, dynamic options like page.waitForSelector() or page.waitForNavigation(). These methods wait for specific conditions to be met, like an element becoming visible or the page fully loading.

  • Use Conditional Waits: Leverage waits that only pause execution when necessary, such as waitForSelector(). These adapt to the actual load times of elements and actions in your application.
await page.waitForSelector('#submit'); // Waits only until the element appears
  • Set Custom Timeouts: You can define custom timeouts for waits to avoid indefinite waiting or premature test failures.
await page.waitForSelector('.loading', { timeout: 5000 }); // Waits up to 5 seconds
  • Rely on Auto-Waiting: Playwright auto-waits for elements to become ready (for example, clickable), reducing the need for manual waits.

Talk to an Expert

Best Practices to Manage Delays and Async in Playwright

Asynchronous programming in Playwright allows your test scripts to run efficiently without blocking other operations. It handles dynamic content by waiting for certain events like page loads, API responses, or element visibility.

Using async/await ensures that actions are complete before moving forward, improving reliability.

Here are the best practices to manage delays and async in Playwright.

  • Use the Correct Wait Strategy: Always use dynamic waits such as waitForSelector() or waitForLoadState(). These methods only pause the test execution until the condition is met, making your tests more efficient and avoiding the pitfalls of hard waits.
  • Wait for Global State: Global state refers to the overall readiness of the application, like page load or app initialization. Ensure that the application is fully loaded and all resources (for example, scripts and images) are available before interacting with elements. page.waitForLoadState() is useful in these scenarios.
  • Embrace the State of the Locator: Locators are references to elements on the page. Before performing any action, ensure that the element is not only present but also ready for interaction (e.g., clickable, visible). Use smart locators and dynamic waits to avoid flaky tests.
  • Set a Custom Timeout: In Playwright, every wait has a default timeout (usually 30 seconds). However, depending on their complexity, some operations might need more or less time. Adjust the timeout for operations like form submissions or API calls to match the expected time.
await page.waitForSelector('#submit', { timeout: 10000 }); // 10 seconds
  • Wait for DOM Events: Sometimes, you need to wait for specific events in the DOM, such as DOMContentLoaded or load. These events signal that the page has finished loading specific parts of the content. You can listen to these events and trigger actions accordingly.
  • Use Asynchronous Interactions: In Playwright, every interaction (clicks, inputs, navigation) should be handled asynchronously to avoid blocking other operations. Use await to ensure that the action is completed before the next one starts.
  • Reuse Locators with Dynamic Content: Reusing locators prevents unnecessary waits when dealing with dynamic content. Instead of locating the same element multiple times, use the already defined locators in your tests, reducing redundancy and improving test speed.
  • Run Tests on Real Devices: Testing on real devices, like those offered by BrowserStack Automate, ensures your app works in real-world scenarios. This avoids the pitfalls of environment-specific issues and ensures better cross-browser and device compatibility.

BrowserStack Automate Banner

  • Leverage a Dependency Graph: A dependency graph represents the order in which actions occur, ensuring that steps are executed only when the dependent step is complete. This helps avoid redundant waits and improves test flow.
  • Run Tasks in Parallel: Parallel testing on platforms like BrowserStack Automate can significantly speed up your test runs, allowing multiple tests to run simultaneously across different devices and browsers.

Why Run Playwright Tests on Real Devices?

Running Playwright tests on real devices ensures accurate testing across diverse environments in real user conditions, reducing the chance of missing bugs caused by environment-specific issues. This will also ensure that test scripts created handle the dynamic nature of the application that can be easily done with playwright wait.

BrowserStack offers a real device cloud platform for testing on different devices. This platform allows you to access over 3,500+ different devices, browsers, and OS combinations. Thus, you can run the same tests on multiple device-browser combinations, saving time and ensuring maximum test coverage.

Use wait strategies effectively in Playwright as they are crucial for creating stable, reliable, and performant tests. Avoid common pitfalls like flaky tests and hard waits by leveraging dynamic waits and best practices.

Using platforms like BrowserStack further enhances your testing by allowing tests to run on real devices, ensuring true cross-browser compatibility.

Try BrowserStack Automate Now

Tags
Automation Testing Playwright

Featured Articles

Mastering End-to-End Testing with Playwright and Docker

Mastering Test Automation with Playwright Java

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers