0
0
Cypresstesting~5 mins

Hidden elements handling in Cypress

Choose your learning style9 modes available
Introduction

Sometimes elements on a webpage are hidden but still important to test. Handling hidden elements helps ensure your tests check everything correctly.

When a button is hidden and only appears after a user action like hover or click.
When testing a dropdown menu that is hidden until clicked.
When verifying if a hidden input field holds the correct value.
When you want to check if an element is hidden or visible as part of UI behavior.
When testing modals or popups that start hidden and appear later.
Syntax
Cypress
cy.get('selector', { timeout: 10000 }).should('not.be.visible')
cy.get('selector', { force: true }).click()

Use { force: true } to interact with hidden elements.

Use assertions like .should('not.be.visible') to check if elements are hidden.

Examples
Check that the button with id hiddenButton is hidden.
Cypress
cy.get('#hiddenButton').should('not.be.visible')
Click the hidden button by forcing the action.
Cypress
cy.get('#hiddenButton', { force: true }).click()
Verify dropdown menu is hidden, click toggle, then verify it is visible.
Cypress
cy.get('.dropdown-menu').should('not.be.visible')
cy.get('.dropdown-toggle').click()
cy.get('.dropdown-menu').should('be.visible')
Sample Program

This test visits a page, checks a button is hidden, forces a click on it, then verifies it is visible after the click.

Cypress
describe('Hidden Elements Handling', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })

  it('checks hidden element visibility and forces click', () => {
    // The button is hidden initially
    cy.get('.action-btn').should('not.be.visible')

    // Force click the hidden button
    cy.get('.action-btn', { force: true }).click()

    // After click, check if some visible change happened (example)
    cy.get('.action-btn').should('be.visible')
  })
})
OutputSuccess
Important Notes

Using { force: true } bypasses Cypress's default check for visibility before interacting.

Be careful when forcing actions on hidden elements; it may not reflect real user behavior.

Always verify if the element should be visible after interaction to ensure test reliability.

Summary

Hidden elements can be tested by checking visibility and forcing actions.

Use .should('not.be.visible') to assert hidden state.

Use { force: true } option to interact with hidden elements.