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 β€’ πŸ“– 2 min read
  • twitter
  • facebook

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

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

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:

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

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:

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

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":

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

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
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended