Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 35 ยท Actions and Assertions

Assertions That Retry

How should and web-first expect assertions retry until they pass, when plain expect does not, and how to use soft assertions, polling and timeouts correctly.

A web page is never finished the instant a test looks at it. A request is in flight, a list is rendering, a spinner is about to disappear. If a test asserts "the status says Saved" at the wrong millisecond, it fails even though the app is working. If it waits a fixed two seconds, it is slow when the app is fast and still flaky when the app is slow.

Cypress and Playwright solve this the same way: an assertion on the page keeps retrying until it passes or a timeout runs out. This lesson explains which assertions retry and which silently do not, how to write the retrying kind in each tool, and when to reach for soft assertions, polling and negative checks. It builds on Locators in Playwright and Clicking, Typing and Other Actions.

Real versus stand-in. The Cypress (js) and Playwright (ts) code in static blocks is real and read-only; the site cannot run a browser. The runnable example is a small retry helper written in Node for this lesson. It reproduces the behavior (re-read, compare, retry, give up) but is not either tool's code.

The retry loop

Both tools run the same idea:

flowchart LR
  A["Query the page<br/>(find element, read text)"] --> B["Compare with expected"]
  B --> C{"Passes?"}
  C -- yes --> D["Continue the test"]
  C -- no --> E{"Timeout reached?"}
  E -- no --> F["Wait a short interval"]
  F --> A
  E -- yes --> G["Fail with the last value seen"]

The key detail: every attempt queries the page again. A value captured earlier never changes, so there would be nothing to retry.

The default timeout is 4 seconds for Cypress (defaultCommandTimeout) and 5 seconds for Playwright's expect (expect.timeout). Both are configurable globally and per assertion.

Cypress: should, and, and implicit retries

In Cypress, a query command followed by .should() or .and() forms a retrying unit.

JavaScript
cy.get('[data-cy=status]').should('have.text', 'Saved');

cy.get('[data-cy=cart-row]')
  .should('have.length', 3)
  .and('be.visible');

cy.get('[data-cy=total]').should('contain', '$24.00').and('not.have.class', 'error');

When the assertion fails, Cypress re-runs the query chain (cy.get(...)), then the assertion, until it passes. Commands that perform actions, such as .click(), are not retried this way; they run once, after their own actionability waits. This is why you put assertions right after the query they check.

A callback form lets you write your own check and still get retries:

JavaScript
cy.get('[data-cy=price]').should(($el) => {
  const amount = parseFloat($el.text().replace('$', ''));
  expect(amount).to.be.greaterThan(0);
  expect(amount).to.be.lessThan(1000);
});

Keep callbacks free of side effects, because they may run many times.

The trap: chai expect and then()

A plain expect(...) from chai does not retry; it checks a fixed value once. The same goes for code inside .then():

JavaScript
// Does NOT retry: the text is read once, when .then() runs
cy.get('[data-cy=status]').then(($el) => {
  expect($el.text()).to.equal('Saved');
});

// Retries: the assertion is attached to the query
cy.get('[data-cy=status]').should('have.text', 'Saved');

Use expect inside .should(callback) (which retries) rather than inside .then() (which does not). The same distinction explains why cy.get(...).then(...) followed by another cy.get can race. We look at how the command queue schedules all this in How Cypress Commands Really Work.

Playwright: web-first assertions

Playwright's expect has two personalities. When you pass it a locator or a page and await the result, you get a web-first assertion that retries.

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

test('saves the order', async ({ page }) => {
  await page.goto('/orders/new');
  await page.getByRole('button', { name: 'Save' }).click();

  await expect(page.getByTestId('status')).toHaveText('Saved');
  await expect(page.getByTestId('cart-row')).toHaveCount(3);
  await expect(page.getByRole('link', { name: 'Receipt' })).toBeVisible();
  await expect(page).toHaveURL(/\/orders\/\d+/);
  await expect(page.getByLabel('Email')).toHaveValue('[email protected]');
});

The matchers worth knowing: toBeVisible, toBeHidden, toBeEnabled, toBeDisabled, toBeChecked, toHaveText, toContainText, toHaveValue, toHaveAttribute, toHaveClass, toHaveCount, toHaveURL and toHaveTitle. Each one re-reads the page until the condition holds.

When you pass expect an ordinary value, you get a generic assertion that does not retry:

TypeScript
// Does NOT retry: textContent() resolves once, then toBe compares a fixed string
expect(await page.getByTestId('status').textContent()).toBe('Saved');

// Retries: the locator is re-queried on every attempt
await expect(page.getByTestId('status')).toHaveText('Saved');

This is the single most common mistake in Playwright suites. Prefer the second form every time.

Polling and toPass

Sometimes the value comes from somewhere that is not a locator, such as an API response. expect.poll re-runs an async function until its result satisfies the matcher, and toPass retries a whole block of code.

TypeScript
await expect.poll(async () => {
  const response = await page.request.get('/api/jobs/42');
  return (await response.json()).state;
}, { timeout: 10_000, intervals: [250, 500, 1000] }).toBe('done');

await expect(async () => {
  const text = await page.getByTestId('log').innerText();
  expect(text).toContain('Finished');
}).toPass({ timeout: 8000 });

Negative assertions

"This should not be there" needs care, because it can pass for the wrong reason.

  • Playwright: await expect(locator).not.toBeVisible() (or toBeHidden()) passes when the element is hidden or absent. Use toHaveCount(0) if you specifically mean "not in the DOM". The negative form also retries, so it waits for the spinner to go away.
  • Cypress: .should('not.exist') waits for the element to be gone from the DOM. .should('not.be.visible') requires the element to exist but be hidden, and fails if it does not exist at all.

Pair a negative check with a positive one when you can ("the Saved message appears and the spinner is gone") so a typo in a selector cannot make "nothing found" look like success.

Soft assertions

A normal failed assertion stops the test. A soft assertion records the failure and keeps going, then the test fails at the end listing every problem. Playwright has this built in:

TypeScript
await expect.soft(page.getByTestId('title')).toHaveText('Order list');
await expect.soft(page.getByTestId('count')).toHaveText('3 items');
await expect.soft(page.getByTestId('total')).toHaveText('$24.00');
// all three run; the test fails afterwards if any did

Soft assertions suit "check many independent facts on one page" tests, such as a profile page with ten fields. Do not use them to check something the rest of the test depends on, because a later step would then run in a broken state.

Cypress has no built-in soft mode. Teams chain several .should() calls, or add a plugin that collects failures.

Timeouts

Raise timeouts only for conditions that are legitimately slow, and as narrowly as possible.

JavaScript
cy.get('[data-cy=report]', { timeout: 15000 }).should('be.visible');
TypeScript
await expect(page.getByTestId('report')).toBeVisible({ timeout: 15_000 });

A global timeout of a minute hides slow pages, makes failures take forever and still does not fix a wrong assertion. If you find yourself needing a huge timeout, check what the page is actually waiting for: usually the better move is to assert on that event, such as a network response, as covered in Auto-Waiting in Playwright.

A retrying assertion helper

The stand-in below implements the machinery in Node. A fake "page" changes after 120 ms (status text and spinner) and 200 ms (a new list item). Three helpers mirror real behavior: expectRetrying re-reads a getter on each attempt (like web-first assertions and expect.poll), expectNow compares a fixed value once (like plain chai expect or expect(await ...)), and softGroup collects failures. The timers are real, but the margins are wide, so the results are stable.

Node.js Retry until it passes, or give up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the first two results. Both ask whether the status is Saved, but the first captured the string before the page updated, so it can never pass, while the second keeps asking. The negative check not.toBe(true) waits for the spinner flag to flip. The timeout step shows the failure message you want in real life: the expectation plus the last value seen. Finally, the soft group runs all three checks and reports two failures together.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Playwright line retries until the text matches?

    Web-first assertions take a locator, re-query it on each attempt and retry until the timeout. The other forms read a fixed value once or rely on a fixed sleep.
  2. 2. In Cypress, why might an expect() inside .then() fail even though the page updates a moment later?

    should() and and() retry the query plus assertion. A then() callback runs once with whatever the subject was at that moment.
  3. 3. What does await expect(locator).not.toBeVisible() pass for?

    In Playwright it passes for hidden or absent elements. Use toHaveCount(0) when you specifically mean not in the DOM.
  4. 4. When are soft assertions a good fit?

    A soft assertion records the failure and continues. That is useful for independent checks, but risky if the next step relies on the result.
  5. 5. What does expect.poll do in Playwright?

    expect.poll is for values that do not come from a locator, such as an API response, and it retries the function until the matcher passes or the timeout expires.

Summary

  • Both tools retry assertions by re-querying the page; a value you captured earlier cannot be retried.
  • Cypress: .should() and .and() retry; chai expect and .then() do not.
  • Playwright: await expect(locator).toX() retries; expect(await ...) does not. Use expect.poll and toPass for non-locator values.
  • Negative assertions retry too, but check what "absent" means (not.exist, toHaveCount(0)) and pair them with a positive check.
  • Soft assertions collect independent failures; keep them away from steps that later code depends on.
  • Raise timeouts narrowly, and prefer asserting on the real event the page is waiting for.

Next: Forms, Uploads and Downloads.