Exit course
Chapter 4 of 11 Beginner 6 min read 2 quick checks Updated

Cypress Assertions and Waiting Without Sleeps

Watch this chapter Starts at 2:24 in the 9:03 course video.
On this page
  1. Retry-ability in one paragraph
  2. should, and, and the assertions you will use most
  3. Callback assertions for anything else
  4. Why cy.wait(ms) is the wrong tool
  5. Waiting for things that are not on the page
  6. When retry-ability does not help

Most flaky Cypress suites have the same root cause: a test that guesses how long something takes. This chapter shows how Cypress waits for you, where that stops, and what to do instead of cy.wait(2000).

Retry-ability in one paragraph#

Queries such as cy.get, cy.contains, .find and .its do not look once. When a query is followed by assertions, Cypress re-runs the query and the assertions together until the assertions pass or the timeout expires. The default is 4 seconds (defaultCommandTimeout in the config). Actions such as .click() and .type() also wait, for the element to be visible, enabled and not covered, but an action is not retried after it has happened: Cypress will never click twice.

So the rule is: put the waiting into an assertion about the state you expect, and let Cypress retry it.

should, and, and the assertions you will use most#

.should() takes a Chai assertion name as a string, and .and() is an alias that reads better for a second one. This test checks three things about the same input:

it('chains several assertions on one subject', () => {
  cy.visit('/todo')
  cy.get('[data-test=new-todo]')
    .should('be.visible')
    .and('have.attr', 'placeholder', 'What needs to be done?')
    .and('have.value', '')
})

The ones you will reach for constantly:

Assertion Checks
'be.visible', 'exist', 'not.exist' presence and visibility
'have.length', n how many elements matched
'have.text', s / 'contain', s exact text / text included
'have.value', s an input's value
'have.class', c, 'have.attr', name, value classes and attributes
'be.checked', 'be.disabled' form state

'not.exist' is worth a special note: it retries until the element is gone, which is exactly what you want after deleting something:

it('asserts that something is gone', () => {
  cy.visit('/todo')
  cy.get('[data-test=new-todo]').type('Buy milk{enter}')
  cy.contains('.todo-list li', 'Buy milk').find('.toggle').check()
  cy.contains('button', 'Clear completed').click()

  cy.contains('.todo-list li', 'Buy milk').should('not.exist')
  cy.get('.todo-list li').should('have.length', 2)
})

After clicking "Clear completed", you want to check that the "Buy milk" row has disappeared. Which assertion does that reliably?

not.exist retries until the row is removed from the DOM. not.be.visible needs the element to exist, so it fails once the row is removed. A .then() callback runs once and does not retry, so it can check before the app has re-rendered.

Callback assertions for anything else#

When a string assertion is not enough, pass a function to .should(). Cypress retries the whole function until it stops throwing:

it('asserts on every todo with a callback', () => {
  cy.visit('/todo')
  cy.get('.todo-list li').should(($items) => {
    const texts = [...$items].map((el) => el.innerText.trim())
    expect(texts).to.deep.equal(['Pay electric bill', 'Walk the dog'])
  })
})

Keep these callbacks free of side effects (no clicks, no cy commands inside): they may run many times.

The difference between .should(fn) and .then(fn) matters here. .then() runs its callback once, with whatever the query found at that moment. If you put an expect inside .then() and the page is still updating, the test fails instead of waiting. Use .then() to get a value out (chapter 2) and .should() to check one.

Why cy.wait(ms) is the wrong tool#

cy.wait(2000) always costs two seconds and still fails on the day the server needs 2.1. It hides the real question, which is "what am I waiting for?", and the answer is almost always one of:

  1. Something appears on the page. Assert on it; Cypress retries for up to 4 seconds.
  2. It takes longer than 4 seconds. Raise the timeout for that one query, not globally.
  3. A network request finishes. Wait on the request with an alias (chapter 4).

Case 2 looks like this. The response below is held back for three seconds with delay (a cy.intercept option chapter 4 explains), so the default 4-second timeout would be tight; the query gets six:

it('waits for a slow response without a fixed sleep', () => {
  cy.intercept('GET', '**/comments/*', {
    fixture: 'comment.json',
    delay: 3000,
  }).as('slowComment')
  cy.visit('/commands/network-requests')
  cy.get('.network-btn').click()

  cy.get('.network-comment', { timeout: 6000 })
    .should('contain', 'cypress/fixtures/comment.json')
})

The test finishes as soon as the text appears, after about three seconds, not after six. The timeout option is a ceiling, not a delay. (It uses the fixture file you create in chapter 4; come back to this test after that chapter if you are following along.)

A report page takes 6 to 9 seconds to show its table. The test fails with "Timed out retrying after 4000ms". What is the best fix?

A per-query timeout gives that one slow step room and still finishes the moment the table appears. A fixed wait always costs ten seconds; a global timeout makes every genuine failure in the suite take 15 seconds to report; retries rerun a test that will time out the same way.

Waiting for things that are not on the page#

Not every condition is visible in the DOM. Cypress has queries for the rest, and they retry the same way:

cy.location('hash').should('eq', '#/completed')   // the URL
cy.title().should('include', 'Kitchen Sink')       // the document title
cy.window().its('localStorage.todos-vanillajs')    // anything on window
  .should('exist')

The first line appeared in chapter 2's filter test: after clicking the "Completed" link, the assertion waits until the URL hash changes.

When retry-ability does not help#

Cypress retries the chain of queries leading up to an assertion (since Cypress 12, cy.get().find() is retried as a whole), but it never goes back past an action or a .then(). Two patterns break that:

  • An action between the query and the assertion. In cy.get('.btn').click().should('have.class', 'active'), the click is not repeated, so if the click happened too early the assertion cannot recover. Assert on readiness before acting, for example that a list has loaded, and then act.
  • Reading a value once and asserting later. cy.get('.todo-count').invoke('text').then((t) => ...) captures the text once. If you need the count to change, assert with .should('contain', '2 items left') instead.

If a test still flakes after this chapter, the cause is usually outside your test: a network call you are not waiting for (chapter 4), state leaking between tests (chapter 5), or a real race in the application, which chapter 9 shows an example of.