How to Wait for Elements to Be Visible in Cypress
To verify if an element is visible in Cypress, we can use the should('be.visible')
assertion:
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:
cy.get('.element', { timeout: 10_000 }).should('be.visible')
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
}
})
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')
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
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: