0
0
Cypresstesting~15 mins

Force option for hidden elements in Cypress - Build an Automation Script

Choose your learning style9 modes available
Click a hidden button using force option
Preconditions (1)
Step 1: Locate the hidden button with id 'hidden-btn'
Step 2: Click the hidden button using the force option
Step 3: Verify that clicking the button triggers the expected action (e.g., a message appears)
✅ Expected Result: The hidden button is clicked successfully and the expected message 'Button clicked!' is displayed
Automation Requirements - Cypress
Assertions Needed:
Verify the hidden button is clicked using force option
Verify the expected message 'Button clicked!' is visible after click
Best Practices:
Use cy.get() with proper selector for the hidden element
Use { force: true } option to click hidden elements
Use assertions like .should('be.visible') to verify UI changes
Avoid flaky tests by ensuring elements exist before actions
Automated Solution
Cypress
describe('Force option for hidden elements', () => {
  beforeEach(() => {
    cy.visit('/hidden-button-test')
  })

  it('Clicks hidden button using force option and verifies message', () => {
    // Locate hidden button by id and click with force
    cy.get('#hidden-btn').click({ force: true })

    // Verify the expected message appears
    cy.get('#message').should('be.visible').and('have.text', 'Button clicked!')
  })
})

The test visits the page with the hidden button first.

It uses cy.get('#hidden-btn') to find the button by its id.

The { force: true } option is passed to click() to allow clicking even though the button is hidden.

After clicking, the test checks that the message with id message is visible and contains the exact text Button clicked!.

This ensures the hidden button was clicked successfully and triggered the expected UI change.

Common Mistakes - 3 Pitfalls
Trying to click a hidden element without using the force option
Using incorrect or overly generic selectors for the hidden button
Not verifying the result after clicking the hidden button
Bonus Challenge

Now add data-driven testing with 3 different hidden buttons, each showing a different message when clicked

Show Hint