Understanding Playwright Timeout

Understand and configure Playwright timeouts effectively to avoid flaky tests and ensure smooth, reliable automated testing workflows.

Get Started free
Guide Banner Image
Home Guide Understanding Playwright Timeout

Understanding Playwright Timeout

Playwright is a free end-to-end browser automation tool famous for fast and reliable test execution. Playwright timeout is a powerful feature that helps manage delays in automated testing. It ensures tests remain efficient and avoids unnecessary failures caused by slow-loading elements or network delays.

Overview

What is Playwright Timeout?

Playwright timeout refers to the maximum time Playwright will wait for an action, such as page loading or element interaction, before throwing an error.

When to Use Playwright Timeout?

Use Playwright timeout to handle cases where actions may take longer due to network conditions, slow-loading elements, or dynamic content, ensuring tests don’t hang indefinitely.

It is critical to understand the Timeout provided by any automation tool. In this article, you will learn about the various timeouts that Playwright offers.

What is Playwright Timeout?

Playwright timeout is a feature that defines the maximum time Playwright will wait for specific actions—such as page loads, element interactions, or network requests—before throwing an error. It helps prevent tests from hanging indefinitely when operations take more time than expected.

Without the timeout, the test will become flaky.

Playwright timeout can be classified into two levels:

Timeouts

  • Test timeout
  • Expect timeout

Advanced: Low Level Timeouts

  • Action timeout
  • Navigation timeout
  • Global timeout
  • beforeAll/afterAll timeout
  • Fixture timeout

Now you know all the different types of timeouts that Playwright has. In the next section, you learn about each one with an example.

When to use which Playwright timeout?

In order to write a stable test, you must first understand which timeout to use and when.

Here is a list of different timeouts to be used for various scenarios:

  1. Test timeout
  2. Expect timeout
  3. Action timeout
  4. Navigation timeout
  5. Fixture timeout
  6. Global timeout
  7. Hooks timeout

The below section describes in detail about each timeout:

1. Test timeout

Test timeout is the timeout for a particular test to complete. For example if the test timeout is set to 10 seconds, then the test has to complete its execution within 10 seconds and if it takes more than 10 seconds, the execution will be aborted with timeout exception.

Note that by default, the test timeout in Playwright is set to 30 seconds.

We are using BrowserStack’s demo application for writing the example tests

In the below example, you must set the test timeout for a specific test. This is helpful when you want to override the global timeout and want to set a timeout for a specific test.

import { test, expect } from '../../fixtures/fixtures';

test("example for timeout", async ({page}) => {
   test.setTimeout(2000)
   await page.goto("https://bstackdemo.com/")
   const phone = await page.locator(".shelf-item__title", {hasText:"iPhone 12 Mini", })
   const phoneParent = await phone.locator("..")
   const phonePrice = phoneParent.locator(".shelf-item__price .val b")
   await expect(phonePrice).toHavePrice("699")
 })

2. Expect timeout

Assertion, by default, has 5 seconds of timeout in the playwright.

In the example below, the assertion failed with a timeout of 5 seconds. You can find this information in the Playwright test runner > Call tab.

Assertion Failure

To overwrite this open playwright.config.js{ts} file and add the below object inside defineConfig

expect: {
 timeout: 10000
},

Our playwright.config.js{ts} file will look like below

// @ts-check
const { defineConfig, devices } = require('@playwright/test');

/**
* @see https://playwright.dev/docs/test-configuration
*/
module.exports = defineConfig({
expect: {
 timeout: 10000
},

 testDir: './tests/timeout-examples/',
 /* Run tests in files in parallel */
 fullyParallel: true,
 /* Fail the build on CI if you accidentally left test.only in the source code. */
 forbidOnly: !!process.env.CI,
 /* Retry on CI only */
 retries: process.env.CI ? 2 : 0,
 /* Opt out of parallel tests on CI. */
 workers: process.env.CI ? 1 : undefined,
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
 reporter: 'html',
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
 use: {
   /* Base URL to use in actions like `await page.goto('/')`. */
   // baseURL: 'http://127.0.0.1:3000',

   /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
   trace: 'on-first-retry',
 },

 /* Configure projects for major browsers */
 projects: [
   {
     name: 'chromium',
     use: { ...devices['Desktop Chrome'] },
   },

   {
     name: 'firefox',
     use: { ...devices['Desktop Firefox'] },
   },

   {
     name: 'webkit',
     use: { ...devices['Desktop Safari'] },
   },

 ],
});

By setting the timeout property value inside the expected object, you overwrite the default assertion timeout value globally.

3. Action timeout

Action timeout refers to the maximum time playwright actions like click() can take to complete.

You can set the action timeout at the individual action level as well as the global level.

Below is an example of actionTimeout at the function level.

await page.getByText("Apple").click({timeout: 3000})

Below is the example of actionTimeout at the global level in the playwright.config.js{ts} file

module.exports = defineConfig({

use: {
   actionTimeout: 1 * 10000
 }

})

Note that global timeout will be overridden when specified at individual command/function level

4. Navigation timeout

Navigation timeout specifies the maximum amount that the page navigation can take.

Navigation timeout can be specified at the global level as well as at the individual command level.

Below is an example at the command level.

await page.goto("https://bstackdemo.com/", {timeout: 30000})

Below is an example of navigationTimeout at the global level, in the playwright.config.js{ts} file

module.exports = defineConfig({
use: {
   actionTimeout: 1 * 10,
   navigationTimeout: 1 * 10000,
 }
})

5. Fixture timeout

Playwright uses the concept of test fixtures to establish the environment for each test, providing the test with everything it needs.

Playwright allows the users to create new fixtures. With the Fixture timeout, you can control the maximum time the fixture can take to complete.

By default, the fixture will consider the test timeout.

const test = base.extend<{ slowFixture: string }>({
 slowFixture: [async ({}, use) => {
   // ... perform a slow operation ...
   await use('hello');
 }, { timeout: 60000 }]
});

The Fixture timeout is to ensure the setup and tasks that are relatively slow in the fixtures are isolated from the tests so that the overall test timeout can be kept small, and the slow fixtures will get their own time to complete the tasks.

Talk to an Expert

6. Global timeout

With Global timeout, you can set the maximum timeout for complete test execution.

Setting the Global timeout will ensure there is no over usage of resources. Upon reaching the timeout specified in the global timeout, the execution will be aborted.

Below is the example to set Global timeout in the playwright.config.js{ts} file

export default defineConfig({
 globalTimeout: 60 * 60 * 1000,
});

7. Hooks timeout

Playwright allows the specification of timeout at hook level, beforeEach/afterEach and beforeAll/afterAll.

By default, the hook timeout will be the same as the test timeout, and below example shows how to set timeout at beforeEach and beforeAll level

test.beforeEach(async() => {

//Below code sets the timeout for this hook
 test.setTimeout(60);
 //Setup code
})
test.beforeAll(async() => {

//Below code sets the timeout for this hook
 test.setTimeout(6000);
 //Setup code
})

BrowserStack Automate Banner

How to test Playwright timeout using BrowserStack?

If you are looking to execute Playwright Automation Testing on Cloud using a testing platform like BrowserStack, follow the below steps:

Step 1. Create a folder in your machine, Example, playwright-timeout-example

Step 2. Open the terminal and access the newly created folder

Step 3. Execute npm init and complete the installation

Step 4. Install Playwright by executing the below command in the terminal

npm init playwright@latest

Step 5. Once the installation is complete, you can see the folder tests created in the root folder

Step 6. Create a new file timeoutExample.spec.js

Step 7. Paste the below code and save

import { test, expect } from '../fixtures/fixtures';

test("example for timeout", async ({page}) => {
 await page.goto("https://bstackdemo.com")
   const phone = await page.locator(".shelf-item__title", {hasText:"iPhone 12 Mini",})
   const phoneParent = await phone.locator("..")
   const phonePrice = phoneParent.locator(".shelf-item__price .val b")
   await expect(phonePrice).toHavePrice("699")
   await page.getByText("Apple").click({timeout: 3000})
 })

Step 8. You can update playwright.config.js file with the timeouts given in the above sections

Step 9. To run the playwright test in UI mode, execute the below command.

npx playwright test –-ui

Step 10. Get the username and access key from your BrowserStack account and execute the below command in your terminal

export BROWSERSTACK_USERNAME="YOUR_USERNAME"
export BROWSERSTACK_ACCESS_KEY="YOUR_ACCESS_KEY"

Step 11. Install BrowserStack nodejs sdk and setup username/key with the below command:

npm i2 -D browserstack-node-sdk@latest
npx setup --username "YOUR_USERNAME" --key "YOUR_ACCESS_KEY"

Step 13. Once the installation is complete, there will be a BrowserStack config file, “browserstack.yml” file created at the root of the project. This file contains all the capabilities required to execute tests in BrowserStackCloud

Step 14. Detailed setup instruction can be found here

Step 15. Below command can be executed to run the Playwright tests in BrowserStack cloud

npx browserstack-node-sdk <Your existing command for running your test suite>

Conclusion

You have seen how beneficial it is to specify timeout at various levels and how to set the timeout at individual/Global level. Timeout is very crucial in order to ensure the test will never get into forever looping mode and the application always performs the operation under an expected timeframe.

BrowserStack Automate is an excellent choice for running Playwright tests because it offers a scalable, cloud-based infrastructure that eliminates the need for complex local setups.

With support for real-time cross-browser testing, parallel execution, and integrations with CI/CD pipelines, BrowserStack ensures faster test runs and streamlined workflows. Choose BrowserStack Automate to enhance the reliability and performance of your Playwright test suite with ease.

Try BrowserStack Now

Tags
Automation Testing Website Testing