cypressvisible

How to wait for an element to be visible?


Is it possible to wait until an element is visible?

cy.get('[data-test=submitIsVisible]').should('be.visible');

This should error if the submit button is not visible. I want to wait until the submit button is visible.

The primary use case is visual testing, i.e. taking a screenshot of the page.


Solution

  • You can wait for the element to be visible like so:

    // Give this element 10 seconds to appear
    cy.get('[data-test=submitIsVisible]', { timeout: 10000 }).should('be.visible');
    

    According to Cypress's Documentation:

    DOM based commands will automatically retry and wait for their corresponding elements to exist before failing.

    Cypress offers you many robust ways to query the DOM, all wrapped with retry-and-timeout logic.

    Another way to wait for an element’s presence in the DOM is through timeouts. Cypress commands have a default timeout of 4 seconds, however, most Cypress commands have customizable timeout options. Timeouts can be configured globally or on a per-command basis. Check the customizable timeout options list here.

    In some cases, your DOM element will not be actionable. Cypress gives you a powerful {force:true} option you can pass to most action commands.

    Caveat:

    As Anthony Cregan pointed out, the .should('be.visible') assertion checks whether an element is visible on the page, not necessarily in the viewport. This means that this assertion will return true even if the element is not within the visible area of the screen when the test is run.

    Further recommended readings: