Retry Failed Test Cases in Playwright

Profile picture for user devraj

Playwright Test supports the test retries option, which you can enable using the playwright configuration file or the command line. When enabled, failing tests will be retried multiple times until they pass or until the value given for the retires option is reached.

Table of Contents

  1. Retries Option in Configuration File
  2. Retries Command Line Option
  3. Test Categories During Retry
  4. Detect Retries at Run Time
  5. Video Tutorial

Retries Option in Configuration File

In your playwright.config.js or ts file, add the retries key and value in config json.

const config = {
  // Give failing tests 3 retry attempts
  retries: 3,

Retries Command Line Option

This will override configuration file option value. Test will be retried two times instead of 3.

# Give failing tests 2 retry attempts
npx playwright test --retries=2

Test Categories During Retry

During Retry, Playwright Test will categorize tests as follows:

  • passed: tests that passed on the first run.
  • flaky: tests that failed on the first run but passed when retried.
  • failed: tests that failed on the first run and failed all retries.

You can try the flaky option using the below code. If the random value is less than 5 test will be executed again and displayed in the flaky section in the report.

test.only('Retry Option', async ({ page }) => {
    const num = Math.floor(Math.random() * 11);
    await expect(num).toBeGreaterThan(5)
playwright retry failed test

Flaky Test will be displayed in Flaky section. A New Tab will be created for Test Number of Retries.

Detect Retries at Run Time

If you want to clean the cache or perform any other action when the test fails, you can use testInfo.retry property. You can detect retries at runtime with testInfo.retry, which is accessible to any test, hook, or fixture. It specifies the retry number when the test is retried after a failure. The first test run has testInfo.retry equal to zero; the first retry has it equal to one, and so on. Make sure you add testInfo in test argument.

test.only('capture screenshot', async ({ page }, testInfo) => { 
    if (testInfo.retry)
        console.log('Test has been retried.')

In the above code, when the retry value is not equal to 0, then the if condition will execute.

Video Tutorial: etry Failed Test Cases in Playwright