QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright

Auto-waiting and web-first assertions

Web-first assertions

Web-first assertions check a condition in a loop until it holds or the assertion timeout (5 seconds) runs out. On every attempt the locator finds the element again and compares its state, which makes them more reliable than waitForTimeout. Only matchers on a locator or page retry; toBe over a value taken from textContent() or count() reads once and waits for nothing.

Playwright · Waiting

The message shows up after 300 ms, yet the test is already red. Add waitForTimeout?

A test clicks "Save" and reads the status text right away. Sometimes the "Saved" message is not there yet, the test fails, and the nearest fix is waitForTimeout(1000) before the check. A month later the suite has dozens of pauses, a run is slow, and flaky failures still happen. This lesson is about why waiting built into the assertion beats any pause, how it works, and where it stops helping.

How it works and why. Web-first assertions are expect calls that receive a locator or a page: toBeVisible, toHaveText, toHaveValue, toHaveCount, toHaveURL and others. They do not compare a value that already sits in a variable: they check a condition in a loop. On every attempt the locator finds the element again (a locator is lazy and only stores a description of how to search), reads its state and compares it with the expected one. A match ends the assertion at once. No match: a short pause and a new attempt, until the assertion timeout runs out.

This design solves the main problem: nobody knows in advance when the UI will "catch up". A fixed pause is always either too long (slow run) or too short (unstable test). The loop runs exactly as long as needed: a fast app passes in milliseconds, a slow one gets headroom up to the timeout.

One read versus a repeated check

text appears textContent() + toBeFAILone read toHaveTextOKretries until it matches
Figure 1. Each circle is one read of the element. A plain toBe reads once; a web-first assertion keeps reading until it matches or the timeout ends.

The assertion timeout defaults to 5 seconds. It is a separate limit, not to be confused with the test timeout (30 seconds). Change it in the config via expect.timeout or for a single call with the timeout option. await always precedes expect, because the assertion returns a promise.

// playwright.config.ts
export default defineConfig({
  expect: { timeout: 10_000 },   // for all web-first assertions
});

// in a test
await expect(page.getByRole('status')).toHaveText('Done');
await expect(page.getByRole('alert')).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole('dialog')).not.toBeVisible();
await expect(page).toHaveURL(/\/orders\/\d+$/);

Example: from a falsely red test to a stable one. The original version reads the text once:

// before
await page.getByRole('button', { name: 'Save' }).click();
const msg = await page.getByRole('status').textContent();
expect(msg).toBe('Saved');

textContent() waits only for the element to appear in the DOM, not for the expected text: it returns the value "right now", and if the request is still in flight, msg holds an empty string. After that a plain toBe compares two strings and has nothing to retry. The error looks like this (shortened; exact wording depends on the version):

Error: expect(received).toBe(expected) // Object.is equality

Expected: "Saved"
Received: ""

There is not a word about a timeout in it: a sign that nothing was retried. The fix changes not the "length of the wait" but the kind of check:

// after
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('status')).toHaveText('Saved');

Now a failure, if it happens, looks different, and it shows what Playwright actually saw (also shortened):

Error: expect(locator).toHaveText(expected) failed

Locator: getByRole('status')
Expected: "Saved"
Received: ""
Timeout: 5000ms

There is a Locator and a Timeout, and Received shows the last observed value. If it is still empty after 5 seconds, the problem is not synchronisation but the app: the message really did not appear.

What replaces what. Every method that returns a value "right now" has a web-first counterpart:

Reads onceRetries until the timeout
expect(await el.isVisible()).toBe(true)await expect(el).toBeVisible()
expect(await el.textContent()).toBe('Ok')await expect(el).toHaveText('Ok')
expect(await el.inputValue()).toBe('42')await expect(el).toHaveValue('42')
expect(await el.count()).toBe(3)await expect(el).toHaveCount(3)
expect(page.url()).toContain('/orders')await expect(page).toHaveURL(/orders/)

The difference is subtle: toHaveText('Ok') compares the whole text (whitespace is normalised), while toContainText('Ok') looks for a substring. For a list, pass an array: toHaveText(['Apple', 'Pear']) waits for the same number of elements with texts matching in order.

Disappearing and absence. Negative checks retry too. await expect(spinner).toBeHidden() waits until the element becomes invisible or leaves the DOM, and not.toBeVisible() behaves the same. To tell "in the DOM but hidden" from "not in the DOM", use toBeAttached() and not.toBeAttached(). A typical loader pattern: first wait for the spinner to go away, only then check the data.

Limits. Only matchers that work with a locator or a page retry. General toBe, toEqual, toContain compare a ready value and wait for nothing. The same goes for isVisible(), textContent(), count(): they answer "what is now", and Playwright explicitly advises against building checks on them. If the value does not come from a locator (an API response, a file), you need expect.poll or toPass: the topic of a separate lesson. One more limit: an assertion waits only up to its own timeout; if the app really answers in 20 seconds you can raise the limit, but first find out why it is so slow.

Comparison with other tools. In Cypress, should commands retry automatically too, the idea is the same. Selenium has nothing like this out of the box: you write a WebDriverWait with a condition, and it is easy to forget or to wrap in the wrong place. So Playwright's "waits by itself" applies to assertions, not to arbitrary JavaScript around them.

Common mistakes.

  • Forgetting await before expect(locator): the test may end before the check does, and the error shows up later or gets lost.
  • Taking values via textContent(), isVisible(), count() and comparing them with a plain toBe: the check reads once and is unstable.
  • Raising expect.timeout to 30 seconds "so it stops failing": a slow app is not cured, and a real defect (the message never appears) is found half a minute later.
  • Putting waitForTimeout before an assertion: the pause adds no reliability, and the run gets slower with every use.
  • Checking the spinner is gone via isVisible() right after a click: the spinner has not appeared yet, so the check passes by mistake.

Check yourself

A product list loads from an API. The test does expect(await page.getByRole('listitem').count()).toBe(5) and fails with "Received: 0", although the app shows 5 products. What is the cause and what should change?

Answer

count() returned a number at a moment when the API response had not arrived yet, and toBe retries nothing. Replace the check with await expect(page.getByRole('listitem')).toHaveCount(5): then the count is re-read until it becomes 5 or the timeout ends.

The assertion expect(page.getByRole('alert')).toBeVisible() without await is the last line of a test, and there is no banner. Why can the test be green?

Answer

Without await the test does not wait for the assertion's promise and finishes before the check can fail. At best the error surfaces later as an unhandled rejection, at worst nothing is verified. That is why await is mandatory, and the linter rule no-floating-promises helps not to forget it.

In an interview. Junior: For checks I use web-first assertions with a locator, such as toHaveText: they retry the check up to the timeout themselves, so no pauses are needed. Values taken via textContent() or isVisible() do not retry. Middle/Senior: The assertion re-reads the element on each attempt because the locator is lazy, and it has its own timeout (5 s), separate from the test timeout. So toBe over a value taken once is unstable, and waitForTimeout only hides the problem. If what I wait for is not UI but an API or a file, I switch to expect.poll or toPass.

Actionability: what exactly is checked before an action

Before click Playwright checks the element is visible, stable, enabled and not covered; before fill, only that it is visible, enabled and editable. The set of checks depends on the action. If a check fails, Playwright waits and retries until the timeout, so extra pauses are unnecessary. The cause of a timeout is in the call log, which names the failed check and the blocking element.

Playwright · Waiting

The button is on screen, yet the click fails with a timeout. Doesn't Playwright "wait by itself"?

A test clicks "Buy" and fails 30 seconds later. In the report screenshot the button is in place, not disabled, and nothing is animating. The cause is usually one thing: before a click Playwright runs a set of checks, and one of them did not pass before the time ran out. That set is called actionability. Below: how it works, why it is designed this way, and how to find the culprit from one line of the log.

How it works and why. A user does not click a button that has not been drawn yet, that is sliding across the screen, or that is covered by a banner. Playwright models this: before an action it checks that the element is in a state where a person could work with it, and if not, it waits and checks again until the timeout. Hence the main design choice: waiting is built into every action instead of being left to the test author. In Selenium you write the explicit wait (WebDriverWait) yourself, and it gets forgotten; Cypress has similar checks too (the element must be visible, not covered, not disabled), but the set and the behavior differ, so do not carry habits over.

The loop of checks before an action

1 attached 2 visible 3 stable 4 receives events 5 enabled any "no":wait andtry again all "yes" timeis out the action runs timeout:error + log
Figure 1. The checks run as a loop with only two exits: the action or the timeout. The set differs per action, and the order is approximate.

Which checks run. All actions wait for the element to be attached to the DOM, and beyond that the set depends on the action:

ActionWhat Playwright waits for
click, check, uncheck, setChecked, tapvisible, stable, receives events, enabled, not inert
hover, dragTovisible, stable, receives events
fill, clearvisible, enabled, editable, not inert
selectOptionvisible, enabled, not inert
screenshotvisible, stable
  • Visible: a non-empty bounding box and no visibility: hidden. An element with zero size or display: none is invisible, while one with opacity: 0 is considered visible.
  • Stable: the same bounding box in two consecutive animation frames. The reason: a click at a moving target lands "next to" it.
  • Receives events: at the action point there is this very element, not an overlay, modal or spinner covering it.
  • Enabled: the element is not disabled (including fieldset disabled and aria-disabled="true").
  • Editable: enabled and not readonly.
  • Not inert: the element is not inside a subtree with the inert attribute (since 1.65): a user cannot interact with such an element.

Before a click the element is also scrolled into view.

Example: the test fails and we read the log. A cookie banner has just appeared and covers the bottom part of the screen.

// before: hoping that it "will somehow pass"
await page.goto('/product/42');
await page.getByRole('button', { name: 'Buy' }).click();
Error: locator.click: Timeout 30000ms exceeded.
Call log:
  - waiting for getByRole('button', { name: 'Buy' })
  -   locator resolved to <button class="buy">Buy</button>
  - attempting click action
  -   waiting for element to be visible, enabled and stable
  -   element is visible, enabled and stable
  -   scrolling into view if needed
  -   <div class="cookie-banner">…</div> intercepts pointer events
  - retrying click action
  -   waiting 20ms

The log is shortened: the real output has more service lines (scrolling, full selectors, attempt counters), and the wording depends on the Playwright version.

How to read it. The "locator resolved to" line says the element was found, so the locator is not the problem. "visible, enabled and stable" already passed. Only the fourth check failed: "intercepts pointer events" names the obstacle. Then comes "retrying" (the loop from the figure). So in this case neither a longer pause nor another locator will help.

// after: remove the obstacle the way a user would
await page.getByRole('button', { name: 'Accept' }).click();
await page.getByRole('button', { name: 'Buy' }).click();

Two ways to "fix" a covered button

Typical

click({ force: true })

The checks are skipped and the click goes to the button's coordinates. The test is green although a user cannot press the button: the banner bug stays unnoticed.

Better

Close the overlay or wait for it to go away

The test does what a person does. If the banner can no longer be closed, the failure shows a real defect.

Figure 2. The same red test can be "fixed" in two ways, and only the second hides nothing.

force and trial. force: true skips the actionability checks: useful only for unusual elements that react to the event correctly although they are formally "covered". trial: true does the opposite: it passes all the checks but does not perform the action, so you can wait for readiness, for example before a hover menu, or verify that a button is really clickable.

await page.getByRole('menuitem', { name: 'Profile' }).hover({ trial: true });

Timeouts. How long an action waits is set by actionTimeout. It defaults to 0, meaning no separate limit, so the action waits until the timeout of the whole test (30 seconds) is used up. A single hung action eats the whole budget and the error arrives late. That is why people often set use: { actionTimeout: 10_000 } in the config: the failure is fast, and the log is the same.

Navigation. It has separate rules: page.goto waits for the load event by default, and waitUntil changes the readiness moment (domcontentloaded, commit). The networkidle option is officially discouraged: with polling, WebSockets or analytics there may be no "silence", and when there is, it is still not UI readiness. The page.waitForNavigation method is outdated. After an action that changes the URL, verify the result: await expect(page).toHaveURL(/orders/) or page.waitForURL. If you need a specific API response, create the wait before the action:

const responsePromise = page.waitForResponse(
  (res) => res.url().includes('/api/orders') && res.request().method() === 'POST',
);
await page.getByRole('button', { name: 'Place order' }).click();
const response = await responsePromise;
expect(response.status()).toBe(201);

Limits. Actionability guarantees that the element is ready for the action, not that the needed data or text has appeared in it: web-first assertions exist for that. It does not wait for a request to finish. If the element is not in the DOM yet, the loop just keeps spinning until the locator finds it or the timeout runs out. And it cannot tell "the banner is still disappearing" from "the banner will never disappear": the second case remains a real defect.

Common mistakes.

  • force: true against "intercepts pointer events": the check is off, the bug is hidden, and in production the button is unreachable.
  • waitForTimeout before a click: Playwright already waits, and a pause only slows things down without guaranteeing readiness.
  • networkidle as "the page has loaded": on live pages it is unreliable.
  • No actionTimeout: a hung action eats 30 seconds and the cause gets lost in a long log.
  • Expecting actionability to wait for text or data: it checks the state of the element, not its content.

Check yourself

The log has "element is visible, enabled and stable", then right after it "intercepts pointer events" and a timeout. Will raising the timeout to 60 seconds help?

Answer

No, if the covering element does not go away by itself: the "receives events" check will never pass, and Playwright will just retry for longer. You need to find out what that element is (the log names it) and close it or wait until it disappears. A longer timeout helps only when the overlay is temporary, such as a spinner.

How does locator.fill() differ from click() in its set of checks, and why is that logical?

Answer

fill does not need stable and receives events, but it needs editable: a field can be filled without clicking a point, but not if it is readonly. The set depends on what the action itself requires.

In an interview. Junior: Before a click Playwright itself waits for the element to be visible, stable, enabled and not covered, so separate pauses are not needed. Middle/Senior: On a timeout I read the call log: it shows which check failed and which element covers the target. I almost never use force: true, because it hides a real defect (a user cannot click either), and instead of networkidle I wait for a concrete result: a URL, an element or an API response. I set actionTimeout so that failures are fast.

expect.poll and toPass: retries for your own logic

A value that does not come from a locator, such as a status in an API or database, is re-read with expect.poll. It calls a function that returns the value and applies the matcher to each result until it matches. toPass repeats a whole block of steps and assertions. The default timeout of toPass is 0, so it is set explicitly, and only idempotent actions go into the block.

Playwright · Waiting

An order status changes on the backend within seconds, but the UI never shows it. What do you wait for?

After payment the page says "Thank you", but the order becomes PAID only once the backend has processed the payment: a second, sometimes ten. There is no locator to hang toHaveText on: the status lives in an API or a database. The typical "fix" is waitForTimeout(5000) and one request after it. It is either needlessly slow or, in a loaded environment, still not enough. This lesson covers two tools that repeat a check where a web-first assertion does not apply: expect.poll and toPass.

How it works and why. A web-first assertion retries because it knows what to repeat: re-read the element by its locator. A plain expect(value) receives a ready value, so there is nothing to repeat. Playwright offers two ways to bring re-reading back. expect.poll takes a function that returns a value and calls it again and again, applying a matcher to each result. toPass takes a block of code with assertions and repeats it whole until the block finishes without an error. Both have a timeout and a list of intervals between attempts, so the app is not hammered in a tight loop.

expect.poll: polling a value. The function only has to return the current value; the matcher does the assertion:

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

test('order becomes PAID after payment', async ({ page, request }) => {
  await page.goto('/checkout');
  await page.getByRole('button', { name: 'Pay' }).click();
  const id = await page.getByTestId('order-id').innerText();

  await expect
    .poll(
      async () => {
        const res = await request.get('/api/orders/' + id);
        return (await res.json()).status;
      },
      {
        message: 'the order must become PAID',
        timeout: 30_000,
        intervals: [500, 1000, 2000],
      },
    )
    .toBe('PAID');
});

Without intervals the pauses between attempts grow: 100, 250, 500, 1000 ms, then stay at 1000. Without timeout the value of expect.timeout (5 seconds) is used, so for slow processing you set it explicitly. Ordinary matchers are supported (toBe, toEqual, toBeGreaterThan, toContain, not), but locator matchers such as toBeVisible are not, because the value is no longer an element. When time runs out, message becomes part of the error message.

toPass: repeating a whole block. When a check needs several steps, for example "reload the page and look at a row in a table", a function returning a value does not fit. Then you repeat the block:

await expect(async () => {
  await page.reload();
  await expect(page.getByRole('row', { name: 'Report 42' })).toContainText('Ready', {
    timeout: 1000,
  });
}).toPass({ timeout: 20_000, intervals: [1000, 2000] });

A catch: toPass has a default timeout of 0, meaning it does not take expect.timeout and retries until the test's own time runs out. So always set the limit. Give the inner assertions short timeouts too: otherwise one iteration can take 5 seconds, and in 20 seconds you get only a few attempts.

Web-first assertionexpect.polltoPass
What is repeatedThe locator checkA call of a function that returns a valueThe whole block of actions and assertions
When to useUI stateAPI, DB, file, any valueA sequence of actions that must be repeated
Default timeout5 s (expect.timeout)5 s (expect.timeout)0, i.e. until the test ends

Example: from a pause to poll. The original waits blindly:

// before
await page.getByRole('button', { name: 'Pay' }).click();
await page.waitForTimeout(5000);
const res = await request.get('/api/orders/' + id);
expect((await res.json()).status).toBe('PAID');

When processing is fast, the test idles for 5 seconds for nothing; when it takes 6, the test fails with "Expected: PAID, Received: PENDING". Replacing it with expect.poll looks like the example above: the test finishes the moment the status becomes PAID, and the upper bound (30 seconds) shows that the wait is a deliberate limit, not a guess. If the status has not changed in 30 seconds, it is no longer a synchronisation problem but a real bug or an unavailable queue.

The danger of repeated actions. Inside toPass actions run on every attempt. Put "Pay" or any POST there and they repeat, producing a duplicate:

Where to put the action relative to toPass

Typical

Action inside toPass

Attempt 1: click, no confirmation yet, the block fails. Attempt 2: click again. Attempt 3: one more. The system holds several orders, and the test is green.

Better

Action outside toPass

The click runs once. Only the check (an assertion or a read request) repeats; it changes nothing, so any number of attempts is safe.

Figure 1. A repeated block has room only for idempotent steps: reading, refreshing, navigating.
// BAD: every iteration creates one more order
await expect(async () => {
  await page.getByRole('button', { name: 'Place order' }).click();
  await expect(page.getByText('Order created')).toBeVisible({ timeout: 1000 });
}).toPass({ timeout: 10_000 });

// GOOD: the action once, only the check repeats
await page.getByRole('button', { name: 'Place order' }).click();
await expect(page.getByText('Order created')).toBeVisible();

Limits and alternatives. Polling does not replace proper synchronisation with the UI: if the needed value is visible on the page, a web-first assertion with a locator is shorter and reads better. The function in poll must have no side effects (GET, not POST), because it is called many times. Polling loads the backend, so intervals are not made too short, and the timeout is tied to the expected processing time (for example the queue's SLA), not "with a margin". If processing takes minutes, such a test is better moved to a lower level or checked another way. Other tools do something similar with FluentWait in Selenium or a recursive cy.request in Cypress, but in Playwright repetition, intervals and messages are built in.

Common mistakes.

  • Using poll or toPass where an ordinary web-first assertion is enough: needless complexity and a worse report.
  • Not setting a toPass timeout: the test "hangs" until its own limit, and the real cause is lost.
  • Putting a non-idempotent action (payment, creation) in the block: duplicate data and a falsely green test.
  • Writing your own loop with waitForTimeout inside the poll function: retrying is already built in.
  • Intervals that are too short on a slow backend: the test creates load itself.

Check yourself

A toPass block contains a click() on "Submit" and an assertion for a success message. Why is it dangerous and how do you rewrite it?

Answer

If the assertion does not pass on the first attempt, the block repeats together with the click, so the form may be submitted several times. Move the click before toPass (or keep only the assertion, which retries by itself), and leave only reading or an idempotent refresh in the block.

Why does expect.poll(() => fetchStatus()).toBe('PAID') fail after 5 seconds although processing takes 12?

Answer

The poll timeout defaults to expect.timeout, i.e. 5 seconds. For slow processing set it in the second argument: { timeout: 30_000 }. For toPass the default is 0, so there the thing to remember is the opposite: set a limit.

In an interview. Junior: When I wait not for an element but for a value from an API, I use expect.poll: it calls a function until the value matches the expected one. Middle/Senior: To repeat a sequence of steps I use toPass and always give it a timeout, because by default it is 0 and bounded only by the test. I put only idempotent actions in the block, otherwise a retry creates duplicates. I pick intervals and the upper bound to match the real processing time, so I neither load the backend nor hide a real bug behind a long pause.

Soft assertions, messages and custom matchers

On failure expect.soft does not stop the test but records the error, so one run shows all the mismatches in the report while the test still ends red. Soft is used for independent result checks, while preconditions stay a regular expect to avoid a cascade of false failures. A message goes in the second argument of expect, and repeated checks move into custom matchers with expect.extend.

Playwright · Waiting

A product card with six fields: fix one and the test fails on the next. How do you see them all at once?

A test checks a product card: price, SKU, photo, button. It fails on the price. The developer fixes it, reruns, and now the SKU fails. Then the photo. Three runs to see three small mismatches that were visible from the start. The reason is that a plain expect throws and stops the test at the first failure. That is right for preconditions but wasteful for a set of independent checks. This lesson covers expect.soft, custom messages, expect.configure and expect.extend.

How it works and why. expect.soft checks exactly like a regular assertion (with the same retrying for web-first ones), but on failure it does not throw: it records the error and lets the test move on. At the end the test is marked as failed, and the report shows all recorded mismatches together. The design is logical: one field failing does not make the other fields unclear, so stopping gains nothing and a run costs time.

Three mismatches: how many runs it takes

expect

Run 1: the price fails, the rest is unchecked. Run 2: the SKU fails. Run 3: the photo fails. Three launches, three fixes one by one.

expect.soft

One run: the report holds the price, the SKU and the photo together. All mismatches are visible at once and can be fixed in one iteration.

Figure 1. Soft does not make a test softer: it stays red, the report is just complete.
await expect.soft(page.getByLabel('Name')).toHaveValue('Rostyslav');
await expect.soft(page.getByLabel('Email')).toHaveValue('r@test.com');
await expect.soft(page.getByLabel('Phone')).toHaveValue('+380501112233');
expect(test.info().errors).toHaveLength(0);
await page.getByRole('button', { name: 'Save' }).click();

The expect(test.info().errors) line is a safeguard: if the soft assertions have already failed, going on makes no sense, because the next step would work with wrong data. The regular expect stops the test at this point, and test.info().errors holds all the soft failures recorded earlier.

Example: what is soft and what is not. The original version uses regular assertions:

// before: the first failure hides the rest
await page.goto('/products/42');
await expect(page.getByTestId('price')).toHaveText('1,250 UAH');
await expect(page.getByTestId('sku')).toHaveText('SKU-42');
await expect(page.getByRole('button', { name: 'Add to cart' })).toBeEnabled();

When rewriting, split the checks into two kinds. Preconditions: without them the rest is meaningless (the page opened, the heading is there). They stay regular, because otherwise a failed navigation makes every later assertion fail and fills the report with a dozen identical errors. Independent result checks: each says something of its own, so they become soft.

// after
test('product page shows all data', async ({ page }) => {
  await page.goto('/products/42');
  await expect(page.getByRole('heading', { level: 1 })).toBeVisible();   // precondition

  await expect.soft(page.getByTestId('price')).toHaveText('1,250 UAH');
  await expect.soft(page.getByTestId('sku')).toHaveText('SKU-42');
  await expect.soft(page.getByRole('img', { name: 'Product photo' })).toBeVisible();
  await expect.soft(page.getByRole('button', { name: 'Add to cart' })).toBeEnabled();
});

A custom message. The second argument of expect (and expect.soft) is a string: expect(locator, 'the pay button must be enabled').toBeEnabled(). It appears in the report, and the failure reads without opening the code. This helps most where the assertion itself says little: toBe(true), a check in a loop, expect.poll, where all you see is "the value did not become that".

expect.configure. Returns a configured expect instance with its own timeout or mode. It is cleaner than adding timeout to every call:

const slowExpect = expect.configure({ timeout: 15_000 });
await slowExpect(page.getByTestId('report')).toBeVisible();   // up to 15 seconds

const softExpect = expect.configure({ soft: true });
await softExpect(page.getByTestId('price')).toHaveText('1,250 UAH');

expect.extend: custom matchers. If one check repeats in many tests, move it into a matcher: it returns pass and message (a function), optionally name, expected, actual. A simplified example for a Ukrainian IBAN (29 characters, no checksum validation):

import { expect as baseExpect } from '@playwright/test';

export const expect = baseExpect.extend({
  toHaveValidIban(received: string) {
    const pass = /^UA\d{2}[A-Z0-9]{25}$/.test(received);
    return {
      pass,
      name: 'toHaveValidIban',
      message: () => 'expected a Ukrainian IBAN, received "' + received + '"',
    };
  },
});

// in a test (import our expect instead of the standard one)
expect(await page.getByTestId('iban').innerText()).toHaveValidIban();

Limits and alternatives. Soft does not solve everything. It does not suit places where the next step depends on the previous one: a click after a failed check runs in a wrong state, so between groups of soft assertions you put a "gate" with test.info().errors. The number of soft failures is not limited, and a very long report can hide the main point: split groups of checks into several tests. A custom matcher that works with a ready value does not retry: if you need waiting, build it on web-first assertions or combine it with expect.poll. And for a one-off check a plain function is enough, a matcher is overkill. In the Java world similar behaviour comes from assertAll in JUnit 5 and SoftAssertions in AssertJ.

Common mistakes.

  • Soft on preconditions: a cascade of false failures, and the real cause is hard to find.
  • Soft without checking test.info().errors before an action: the test goes on with a corrupted state, and side effects have already happened.
  • A custom message on every assertion: noise people stop noticing. It belongs where the assertion itself is unclear.
  • A matcher for a one-off check: a plain function reads better.
  • Importing the standard expect from @playwright/test instead of the extended one: it has no custom matcher, and TypeScript will say so.

Check yourself

A test opens the profile page with expect.soft(page).toHaveURL(/profile/), then runs six soft field checks. Navigation failed. What will the report show and what should change?

Answer

The report will contain the URL failure plus six field failures, because the page is not there: the cascade drowns the real cause. A check without which the rest is meaningless is made a regular expect: the test stops right there, and soft stays for independent result checks.

A test with three soft assertions reached its last line, yet the report shows it red. Is that a runner bug?

Answer

No: soft assertions do not throw at once, they record the error, and at the end the test is marked failed. All recorded failures sit in test.info().errors and show in the report. A red status after a soft failure is expected: soft changes the moment of stopping, not the result.

In an interview. Junior: expect.soft does not stop the test at the first failure, so the report shows all mismatches in one run; the test still ends red. Middle/Senior: I use soft for independent result checks and keep preconditions regular, so there is no cascade of false failures. Before an action that depends on the checks I look at test.info().errors. I add messages to non-obvious assertions, take a configured timeout through expect.configure, and move repeated checks into matchers via expect.extend.