Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTesting

Give one Playwright step its own timeout

Pass a timeout option to test.step so a slow step fails in seconds with its own name, instead of burning the whole test timeout.

One of your Playwright tests has four steps, and the second one, a search that waits on an API, hangs now and then. The test timeout is 30 seconds, so every time it hangs you wait the full 30 seconds, and the failure names the test rather than the step.

Playwright 1.50 added a timeout option to test.step. Give the slow step its own limit in milliseconds.

Give the slow step its own clock

import { test, expect } from '@playwright/test'

test('search then checkout', async ({ page }) => {
  await page.setContent(`
    <input type="search">
    <button>Add to cart</button>
    <script>
      document.querySelector('input').oninput = () => {
        setTimeout(() => {
          const link = document.createElement('a')
          link.href = '#product'
          link.textContent = 'Desk lamp'
          document.body.append(link)
        }, 2000)
      }
      document.querySelector('button').onclick = () => {
        const status = document.createElement('p')
        status.textContent = '1 item'
        document.body.append(status)
      }
    </script>
  `)

  await test.step('search for the product', async () => {
    await page.getByRole('searchbox').fill('lamp')
    await page.getByRole('link', { name: 'Desk lamp' }).waitFor()
  }, { timeout: 1_000 })

  await test.step('add to cart', async () => {
    await page.getByRole('button', { name: 'Add to cart' }).click()
    await expect(page.getByText('1 item')).toBeVisible()
  })
})

The sample page takes two seconds to display the link. Save the test as checkout.spec.ts in a Playwright Test project and run it to see the step timeout.

TimeoutError: Step timeout of 1000ms exceeded.

The search step fails after one second, and the checkout step never starts. Reduce the page’s delay to 200 ms and rerun to see both steps pass.

How the timeouts interact

The default step limit is 0, which adds no deadline. The test timeout still applies, and individual actions and assertions can have their own limits.

Let a timeout fail the test. Catching the error does not cancel work the step has already started.

I use it on steps that call a third-party service and on steps that wait for a background job to show up in the UI. I also use it on the first step of a flow, where a slow login would eat the budget of the steps after it. Each gets a limit a little above what it takes on a normal day, and the test timeout stays at the default.