0
0
Cypresstesting~15 mins

Hidden elements handling in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Hidden elements handling
What is it?
Hidden elements handling in Cypress means working with parts of a web page that are not visible to the user. These elements might be hidden by CSS styles or not rendered on the screen but still exist in the page's code. Testing hidden elements helps ensure that the application behaves correctly even when some parts are not shown. It involves special commands and options to find, interact with, or check these hidden parts.
Why it matters
Without handling hidden elements, tests might miss bugs or give false results because they only check visible parts. Many web apps use hidden elements for menus, modals, or data storage, so ignoring them can cause missed errors or broken features. Properly testing hidden elements ensures the app works as expected in all states, improving quality and user experience.
Where it fits
Before learning hidden elements handling, you should know basic Cypress commands for finding and interacting with visible elements. After this, you can learn about advanced Cypress features like custom commands, stubbing, and testing dynamic UI changes.
Mental Model
Core Idea
Hidden elements handling means telling Cypress to find and work with page parts that are not visible but still exist in the code.
Think of it like...
It's like checking behind a curtain on a stage to see if props are in place, even though the audience can't see them yet.
Page DOM Structure
┌───────────────────────────┐
│ Visible Element           │
│ ┌─────────────────────┐ │
│ │ Hidden Element       │ │
│ │ (display:none, etc.) │ │
│ └─────────────────────┘ │
└───────────────────────────┘

Cypress normally sees only the outer box but can be told to look inside the hidden box.
Build-Up - 6 Steps
1
FoundationUnderstanding Visible vs Hidden Elements
🤔
Concept: Learn what makes an element visible or hidden in a web page.
Web pages have elements that can be shown or hidden using CSS properties like 'display:none', 'visibility:hidden', or by being off-screen. Visible elements can be seen and interacted with by users, while hidden elements exist in the code but are not shown on the screen.
Result
You can identify which elements are visible or hidden by inspecting their CSS styles.
Knowing the difference between visible and hidden elements is essential because it affects how tests find and interact with page parts.
2
FoundationBasic Cypress Element Selection
🤔
Concept: Learn how Cypress finds elements by default and interacts with visible ones.
Cypress commands like cy.get() find elements in the page's DOM. By default, Cypress only interacts with visible elements to mimic real user behavior. For example, cy.get('#button').click() clicks only if the button is visible.
Result
Tests fail if you try to interact with hidden elements without special handling.
Understanding Cypress's default behavior helps explain why hidden elements need special handling.
3
IntermediateAccessing Hidden Elements with Cypress
🤔Before reading on: do you think Cypress can interact with hidden elements by default? Commit to yes or no.
Concept: Learn how to tell Cypress to find and interact with hidden elements using options.
Cypress commands accept options like { includeShadowDom: true } or { force: true }. To interact with hidden elements, use cy.get(selector, { includeShadowDom: true }) or cy.get(selector).click({ force: true }). The 'force' option bypasses visibility checks.
Result
You can select and click hidden elements without Cypress throwing errors about visibility.
Knowing how to override Cypress's default visibility checks allows testing of hidden UI parts that affect app behavior.
4
IntermediateAssertions on Hidden Elements
🤔Before reading on: can you assert properties of hidden elements without making them visible? Commit to yes or no.
Concept: Learn how to check the state or attributes of hidden elements without changing their visibility.
Use assertions like cy.get(selector).should('have.attr', 'disabled') or .should('exist') to verify hidden elements. Cypress allows checking attributes and existence even if elements are hidden, but visibility assertions like .should('be.visible') will fail.
Result
You can confirm hidden elements exist and have expected properties without showing them.
Testing hidden elements' attributes helps catch bugs related to state or configuration invisible to users.
5
AdvancedHandling Dynamic Visibility Changes
🤔Before reading on: do you think Cypress automatically waits for hidden elements to become visible? Commit to yes or no.
Concept: Learn how to test elements that change visibility dynamically during user actions or app events.
Use Cypress commands with .should('be.visible') to wait for elements to appear. For hidden elements that become visible after actions, chain commands like cy.get(selector).should('not.be.visible').click({ force: true }) or use cy.wait() carefully. Cypress retries assertions until timeout.
Result
Tests can handle UI changes where elements appear or disappear, ensuring reliable checks.
Understanding Cypress's retry and waiting behavior prevents flaky tests when dealing with dynamic hidden elements.
6
ExpertCustom Commands for Hidden Elements
🤔Before reading on: do you think creating custom Cypress commands improves hidden element testing? Commit to yes or no.
Concept: Learn how to write reusable Cypress commands to simplify hidden element handling across tests.
Define custom commands in cypress/support/commands.js like Cypress.Commands.add('clickHidden', (selector) => { cy.get(selector).click({ force: true }) }). Use these commands to keep tests clean and consistent when interacting with hidden elements.
Result
Your test code becomes easier to read and maintain, reducing duplication and errors.
Creating abstractions for hidden element handling improves test quality and developer productivity.
Under the Hood
Cypress runs inside the browser and accesses the page's DOM directly. By default, it checks if elements are visible before interacting to simulate real user behavior. Hidden elements have CSS properties that prevent them from being visible or interactable. Using options like 'force: true' tells Cypress to skip visibility checks and perform actions anyway. Cypress retries commands and assertions until they pass or timeout, helping with dynamic UI changes.
Why designed this way?
Cypress was designed to mimic real user interactions, so it avoids clicking or typing on hidden elements by default to prevent unrealistic tests. However, web apps often use hidden elements for logic or UI tricks, so Cypress provides options to override this behavior. This balance helps catch real bugs while allowing flexibility for complex apps.
┌───────────────┐       ┌─────────────────────┐
│ Cypress Test  │──────▶│ DOM Element Found    │
└───────────────┘       └─────────┬───────────┘
                                   │
                      Is element visible?
                           ┌──────┴───────┐
                           │             │
                        Yes│             │No (hidden)
                           │             │
               Interact normally       Check if 'force: true'
                           │             │
                           │             │
                      Perform action   Perform action anyway
                           │             │
                      Return success  Return success or error
Myth Busters - 4 Common Misconceptions
Quick: Does Cypress interact with hidden elements by default? Commit to yes or no.
Common Belief:Cypress can click or type on hidden elements just like visible ones without extra options.
Tap to reveal reality
Reality:By default, Cypress refuses to interact with hidden elements and throws errors unless 'force: true' is used.
Why it matters:Tests fail unexpectedly if you assume hidden elements can be interacted with normally, causing confusion and wasted debugging time.
Quick: Can you assert that a hidden element is visible? Commit to yes or no.
Common Belief:You can assert hidden elements are visible if they exist in the DOM.
Tap to reveal reality
Reality:Hidden elements are not visible, so assertions like .should('be.visible') will fail on them.
Why it matters:Misusing visibility assertions on hidden elements leads to false test failures and misunderstanding of UI state.
Quick: Does Cypress automatically wait for hidden elements to become visible before interacting? Commit to yes or no.
Common Belief:Cypress waits for hidden elements to appear and become visible before clicking them.
Tap to reveal reality
Reality:Cypress waits for visibility only if you assert it explicitly; otherwise, it fails immediately if the element is hidden and no 'force' is used.
Why it matters:Assuming automatic waiting causes flaky tests or unexpected failures when UI changes visibility dynamically.
Quick: Is forcing clicks on hidden elements always safe? Commit to yes or no.
Common Belief:Using 'force: true' to click hidden elements is always a good practice.
Tap to reveal reality
Reality:Forcing clicks can cause tests to pass even if the UI is broken or the element should not be interactable, hiding real bugs.
Why it matters:Overusing 'force: true' can mask problems and reduce test reliability.
Expert Zone
1
Hidden elements might be present for accessibility or SEO reasons, so testing their attributes can catch important issues invisible to users.
2
Some hidden elements are inside Shadow DOMs, requiring special Cypress options like 'includeShadowDom: true' to access them.
3
Using 'force: true' bypasses many safety checks, so it should be limited to cases where user interaction is impossible otherwise.
When NOT to use
Avoid forcing interactions on hidden elements when testing user-facing features that require visibility. Instead, test the UI flow that makes elements visible naturally. For complex UI states, use Cypress's waiting and assertion features to handle visibility changes. Alternatives include end-to-end tests that simulate real user behavior without forcing hidden element clicks.
Production Patterns
In real projects, teams create custom Cypress commands to handle hidden elements consistently. They combine visibility assertions with forced actions only when necessary. Tests often check hidden elements' attributes for state validation, like disabled flags or data attributes. Handling Shadow DOM and iframe hidden elements is common in modern web apps, requiring advanced Cypress options.
Connections
Shadow DOM Testing
Builds-on
Understanding hidden elements handling helps when testing Shadow DOM elements, which are often hidden inside encapsulated parts of the page.
Accessibility Testing
Related concept
Hidden elements often affect accessibility; knowing how to test them ensures apps meet accessibility standards.
Optics in Photography
Analogy in a different field
Just like photographers adjust focus to see objects hidden behind obstacles, testers adjust Cypress commands to 'see' and interact with hidden elements.
Common Pitfalls
#1Trying to click a hidden button without forcing interaction.
Wrong approach:cy.get('#hidden-button').click();
Correct approach:cy.get('#hidden-button').click({ force: true });
Root cause:Assuming Cypress clicks hidden elements by default, ignoring visibility checks.
#2Asserting hidden element is visible directly.
Wrong approach:cy.get('#hidden-element').should('be.visible');
Correct approach:cy.get('#hidden-element').should('exist').and('not.be.visible');
Root cause:Confusing existence in DOM with visibility on screen.
#3Overusing 'force: true' on all hidden elements without checking if they should be visible.
Wrong approach:cy.get('.hidden-item').click({ force: true });
Correct approach:cy.get('.hidden-item').should('be.visible').click();
Root cause:Ignoring UI logic and forcing interactions that users cannot perform.
Key Takeaways
Cypress by default interacts only with visible elements to simulate real user behavior.
Hidden elements exist in the DOM but are not shown on screen due to CSS or other reasons.
Use options like 'force: true' to interact with hidden elements when necessary, but use carefully.
Assertions can check hidden elements' existence and attributes but not their visibility.
Handling dynamic visibility and creating custom commands improves test reliability and maintainability.