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 CSSdisplayproperty is set tonone.
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: nonebut missing other CSS properties likevisibility: hiddenoropacity: 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
| Assertion | Description | Usage Example |
|---|---|---|
| not.be.visible | Checks if element is hidden from view | cy.get('selector').should('not.be.visible') |
| have.css 'display', 'none' | Checks if element has CSS display:none | cy.get('selector').should('have.css', 'display', 'none') |
| not.exist | Checks if element is not in the DOM | cy.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.