0
0
CypressHow-ToBeginner ยท 3 min read

How to Assert Element Hidden in Cypress Tests

In Cypress, you can assert that an element is hidden by using cy.get(selector).should('not.be.visible') or cy.get(selector).should('have.css', 'display', 'none'). These commands check if the element is not visible or has CSS styles that hide it.
๐Ÿ“

Syntax

Use cy.get(selector) to find the element, then chain .should() with the assertion:

  • 'not.be.visible': checks if the element is hidden from view.
  • 'have.css', 'display', 'none': checks if the element's CSS display property is set to none.
javascript
cy.get('selector').should('not.be.visible')

// or

cy.get('selector').should('have.css', 'display', 'none')
๐Ÿ’ป

Example

This example shows how to assert that a button with id #submit-btn is hidden on the page.

javascript
describe('Element Hidden Assertion', () => {
  it('checks if the submit button is hidden', () => {
    cy.visit('https://example.cypress.io')
    // Assume the button is hidden by default
    cy.get('#submit-btn').should('not.be.visible')
  })
})
Output
Test passes if #submit-btn is hidden; fails if visible.
โš ๏ธ

Common Pitfalls

Common mistakes when asserting hidden elements include:

  • Using .should('not.exist') instead of .should('not.be.visible'). The element may exist but be hidden.
  • Checking only display: none but missing other CSS properties like visibility: hidden or opacity: 0.
  • Trying to assert visibility on elements not yet rendered or detached from DOM.
javascript
/* Wrong: This fails if element exists but is hidden */
cy.get('#submit-btn').should('not.exist')

/* Right: Checks if element is hidden but exists */
cy.get('#submit-btn').should('not.be.visible')
๐Ÿ“Š

Quick Reference

AssertionDescriptionUsage Example
not.be.visibleChecks if element is hidden from viewcy.get('selector').should('not.be.visible')
have.css 'display', 'none'Checks if element has CSS display:nonecy.get('selector').should('have.css', 'display', 'none')
not.existChecks if element is not in the DOMcy.get('selector').should('not.exist')
โœ…

Key Takeaways

Use cy.get(selector).should('not.be.visible') to assert an element is hidden but present.
Avoid using should('not.exist') when the element is hidden but still in the DOM.
Check CSS properties like display:none to confirm hidden state if needed.
Ensure the element is rendered before asserting visibility to avoid flaky tests.