The same test, run 20 times without changing a line, passed 14 times and failed 6. This lesson shows why, and gives you one question that fixes it: when does this line read the page? Everything follows the official docs (Writing tests, Auto-waiting, Assertions), and every command and output comes from a real run.

What you need

  • Node.js. 22, 24, 26.
  • Playwright 1.65.1. The lesson was recorded with this version; other versions may print slightly different output.
  • The code. Subscribers see the lesson repository in the Source code box under the video. It has two tags: pw02-start to follow along, pw02-end for the finished state.

Step 1: Same test, sometimes red

A delivery person texts "I'll be there in about 10 minutes". You go downstairs at exactly minute 10 and look once. Early delivery: you meet. Traffic: you miss. Waiting until they arrive works every day.

tests/flaky.spec.ts has two tests against a page that answers in a random 700 to 900 ms (?jitter, like a real API). They differ in one place:

// 'sleep then read': guesses the time, looks once
await page.waitForTimeout(800);
const text = await page.getByRole('status').textContent();
expect(text).toBe('Subscribed: a@b.co (Free)');

// 'web-first': keeps asking until it sees the text
await expect(page.getByRole('status'))
  .toHaveText('Subscribed: a@b.co (Free)');

Run each test 20 times:

npx playwright test tests/flaky.spec.ts --project=chromium --repeat-each=20 --workers=1
TestResult over 20 runs (example)
sleep then read14 of 20 (6 failed with Received: "")
web-first20 of 20

Your counts will differ from run to run. A test that passes and fails with no code change is called flaky.

Step 2: The page we test

Start the demo page:

npm run serve

Open http://localhost:4173: a form with Email, Plan, a terms checkbox and a Subscribe button. The slowness is on purpose, like a page waiting for an API. Two delays are built in:

WhenWhat happens
After you click Subscribethe status text appears 800 ms later
After the page loadsthe Pay button stays disabled for 1.5 seconds

Keep this as a ruler: every line of a test reads the page at some moment on this timeline, and the page needs time to catch up.

Step 3: Find, act, check

test('subscribe with email and plan', async ({ page }) => {
  await page.getByLabel('Email').fill('ana@example.com');
  await page.getByLabel('Plan').selectOption('pro');
  await page.getByLabel('I agree to the terms').check();
  await page.getByRole('button', { name: 'Subscribe' }).click();
  await expect(page.getByRole('status')).toHaveText('Subscribed: ana@example.com (Pro)');
});
BeatCodeNotes
FindgetByLabel, getByRolePlaywright reads a tree of roles and names, not pixels: the input is a textbox named Email, the button is a button named Subscribe. That is why getByRole with a name is the most durable locator
Actfill, selectOption, check, clickAlso hover, press, focus, setInputFiles
Checkawait expect(...).toHaveText(...)The status line must have exactly this text

Every line starts with await because every step takes time in the browser. Run it:

npx playwright test tests/subscribe.spec.ts --project=chromium

You should see 2 passed. The page is opened in a hook, which Step 9 explains.

Step 4: Actions wait for the element

Before an action, Playwright checks a list and waits until it passes. For click the list is: exactly one element, visible, stable, receives events, enabled. If it does not pass in time, the action fails with a TimeoutError.

tests/actionability.spec.ts has three tests on the Pay button, which is disabled for 1.5 seconds:

TestWhat it showsResult
click waits for enabledclick() waits until Pay unlockspasses
read once, no waitisEnabled() reads the state oncefails on purpose
click gives upclick({ timeout: 700 }) is shorter than the lockfails on purpose
npx playwright test tests/actionability.spec.ts --project=chromium

Fails on purpose. Two of these three tests are red by design. Red here is the point of the step, not a problem with your setup.

The log of the last test shows how it waits: not continuously, but with growing pauses.

- waiting for getByRole('button', { name: 'Pay' })
  2 × waiting for element to be visible, enabled and stable
  - retrying click action
    - waiting 20ms
  ...
    - waiting 100ms
  ...
    - waiting 500ms

That is why a click can run a little after Pay unlocks: it was inside a pause.

If the element never appears, tests/timeout.spec.ts clicks a Checkout button that does not exist. click has no limit of its own, so it waits until the test limit (30 seconds by default) runs out, then fails.

Step 5: A locator must match exactly one element

Locators are strict: an action aimed at one element fails if the locator matches more than one. tests/strict.spec.ts uses the docs' own example, but the page has two buttons:

await page.getByRole('button').click({ timeout: 1000 });
npx playwright test tests/strict.spec.ts --project=chromium

Fails on purpose. This test is red by design, so you can read a real error:

Error: locator.click: Error: strict mode violation: getByRole('button') resolved to 2 elements:
    1) <button type="submit">Subscribe</button> aka getByRole('button', { name: 'Subscribe' })
    2) <button id="pay" disabled>Pay</button> aka getByRole('button', { name: 'Pay' })

Read an error top to bottom: message, locator, matched elements, source line (line 5 here). Playwright stops at once, because waiting longer cannot turn two buttons into one. It even prints a better locator for each match.

Step 6: Assertions retry

tests/no-await.spec.ts checks the same text in two ways:

// 1. Reads once, then compares
expect(await page.getByRole('status').textContent()).toBe('Subscribed: (Free)');

// 2. Playwright keeps reading until it matches or the timeout is reached
await expect(page.getByRole('status')).toHaveText('Subscribed: (Free)');
Reads the pageResult
textContent()once, right after the clickfails: Received: ""
await expect(...)again and again, until the text appearspasses as soon as the text is there

Same page, only a different moment of reading. The difference is what you hand to expect: a value already read, or a locator Playwright can read again.

The Assertions page says assertions that do not retry (like toBe on a plain value) can lead to flaky tests. Best practices calls the retrying kind web-first and shows this exact pair:

Code
Thumbs upawait expect(locator)
Thumbs downexpect(await ...)

Retrying assertions use a 5 second timeout by default, and you must await them: without it the test moves on without waiting.

Is "asks again" real? tests/wrong-text.spec.ts expects wrong text on purpose; its call log lists every retry: first the status is empty, then it holds different text, then the error.

The retrying assertions you will use most:

TargetAssertions
PagetoHaveTitle, toHaveURL
StatetoBeVisible, toBeEnabled, toBeChecked
ContenttoHaveText, toContainText, toHaveValue
Count and attributestoHaveCount, toHaveAttribute

.not flips any assertion. tests/subscribe.spec.ts uses toHaveValue('') for the empty field, .not.toBeChecked() for the unticked box and toHaveCount(3) for the three features.

Step 7: How long does it wait?

The Timeouts page lists the defaults:

LimitDefault
Whole test30 seconds
Each expect5 seconds
click and other actionsno limit of their own: they wait until the test times out

For a slow step, raise the limit with { timeout } on one assertion, or make your own expect with expect.configure. Do not add a sleep: raise the limit and let Playwright keep retrying.

Step 8: Messages and soft assertions

ToolExampleEffect
Custom messageexpect(locator, 'say we subscribed')Your text is the first line of the error, and the log points at line 5, so a red test on CI says what it checks (tests/message.spec.ts)
Soft assertionexpect.soft(...)The failure is recorded but the test keeps going; in tests/soft.spec.ts the last line still prints reached the last line, and the test ends red with both errors

Step 9: Fresh page and hooks

Each test gets its own BrowserContext, like a brand new browser profile, so the second test sees an empty form even though the first one filled it (the test "starts with a fresh page" checks exactly that). Both subscribe tests open the page with the same goto; the last commit of the lesson moves it into test.beforeEach:

test.describe('subscribe form', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  // ...both tests, without their own goto
});

Still 2 passed.

Tests that fail on purpose

These fail by design, to show real errors. Run them by name to reproduce the video:

FileFails because
actionability.spec.tstwo of three tests (see table above)
no-await.spec.tsfirst test reads once
flaky.spec.tsthe fixed-wait test, some of the time
strict.spec.tsthe locator matches two buttons
wrong-text.spec.tswrong expected text
message.spec.tsexpects Subscribed before anything was submitted
soft.spec.tsthe soft assertions do not match
timeout.spec.tsthe button does not exist

npx playwright test tests/subscribe.spec.ts --project=chromium is the only fully green run of the lesson.

Check your result

  • npx playwright test tests/subscribe.spec.ts --project=chromium → 2 passed
  • npx playwright test tests/strict.spec.ts --project=chromium → strict mode violation

Recap

Kind of lineWhere it sits on the ruler
Read once (textContent())A fixed pin: red if the page is not ready at that moment
Action (click)A sliding pin: waits until the element is ready
await expect(...)Slides too: up to 5 seconds, inside the 30 seconds of the test
  1. A fixed wait guesses how long the page needs; it makes tests flaky.
  2. A locator must match exactly one element.
  3. Raise a limit, never add a sleep.
  4. Each test gets a fresh page; move repeated setup into test.beforeEach.

Next lesson

Next, we go deeper into locators: getByRole, getByText, filtering and chaining.