Element Is Visible

In every example, the button appears on the page only after 1.5 seconds. How would the test confirm the button becomes visible?

📺 Watch this recipe explained in the video Three Ways Of Checking If Element Becomes Visibleopen in new window.

Assertion be.visible

You can use the built-in Chai-jQuery assertionopen in new window be.visible

<button id="a-button" style="display:none">Click me</button>
<script>
  setTimeout(() => {
    document.getElementById('a-button').style.display = 'initial'
  }, 1500)
</script>
cy.get('#a-button').should('be.visible')

Assertion callback

You can use should(callback) and call the Cypress.dom.isVisible utility function to check the element's visibility.

<button id="a-button" style="display:none">Click me</button>
<script>
  setTimeout(() => {
    document.getElementById('a-button').style.display = 'initial'
  }, 1500)
</script>
cy.get('#a-button').should(($el) => {
  // note that the Command Log does not show much information
  // for thrown errors while it retries
  if (!Cypress.dom.isVisible($el)) {
    throw new Error('Element is hidden')
  }
})

Should satisfy assertion

A better variant is to use the Cypress.dom.isVisible predicate function with Chai assertion satisfy

<button id="a-button" style="display:none">Click me</button>
<script>
  setTimeout(() => {
    document.getElementById('a-button').style.display = 'initial'
  }, 1500)
</script>
cy.get('#a-button').should('satisfy', Cypress.dom.isVisible)

Click waits for the element to become visible

Commands like cy.click automatically wait for the element to become visible, no assertions necessary.

<button id="a-button" style="display:none">Click me</button>
<script>
  setTimeout(() => {
    document.getElementById('a-button').style.display = 'initial'
  }, 1500)
</script>
cy.get('#a-button').click()