How can I wait for an element to become visible in Cypress for visual testing without errors?

Is it possible to wait until an element is visible in Cypress?

Currently, I am using:

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

This approach will throw an error if the submit button is not visible. I want to implement a solution to wait until the submit button appears.

The primary use case is for visual testing, such as taking a screenshot of the page. How can I achieve this using cypress wait for element to appear?

Hello Sakshi,

You can wait for an element to be visible in Cypress using the following approach: // 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 automatically retry and wait for their corresponding elements to exist before failing. Cypress provides robust ways to query the DOM with built-in retry and timeout logic.

You can also use timeouts to wait for an element’s presence in the DOM. While Cypress commands have a default timeout of 4 seconds, most commands offer customizable timeout options. These timeouts can be configured globally or for individual commands. You can find the list of customizable timeout options in the Cypress documentation.

In some cases, if a DOM element is not immediately actionable, Cypress provides a { force: true } option that you can use with most action commands.

Caveat:

As noted by Anthony Cregan, the .should(‘be.visible’) assertion checks whether an element is visible on the page, but not necessarily within the viewport. Therefore, this assertion will return true even if the element is not within the visible area of the screen when the test runs.

Hey Sakshi,

You can also set a global timeout for commands by adding the following configuration to your cypress.config.js file:

e2e: { defaultCommandTimeout: 25000, }

Adjust the defaultCommandTimeout value according to your requirements. This will set the default timeout for all commands, allowing you to wait longer for elements to appear.