How to Wait for Elements to Be Visible in Cypress

How to Wait for Elements to Be Visible in Cypress

Ferenc Almasi β€’ 2022 August 15 β€’ Read time 2 min read
  • twitter
  • facebook

To verify if an element is visible in Cypress, we can use the should('be.visible') assertion:

Copied to clipboard!
cy.get('.element').should('be.visible')

As Cypress internally retries commands, we don't need to add any wait clause to ensure the element is visible before verifying it.

By default, Cypress will try to verify if the element is visible in 4 seconds. If you need to increase this timeout, you can pass a timeout property in a configuration object as a second parameter to the cy.get command:

Copied to clipboard!
cy.get('.element', { timeout: 10_000 }).should('be.visible')
Using a custom timeout

Make sure you use timeouts sparingly. Most of the time you will be fine with using the default timeout.

In case you want to globally set a custom timeout, you can do so by changing the e2e.defaultCommandTimeout property inside your cypress.config.js file:

Copied to clipboard! Playground
export default defineConfig({
    ...
    e2e {
        defaultCommandTimeout: 10_000
    }
})
cypress.config.js

How to verify if an element is not visible

You can also verify the opposite and check if an element is not visibly by simply prefixing the assertion with "not":

Copied to clipboard!
cy.get('.element').should('not.be.visible')

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Wait for Elements to Be Visible in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.