top of page

Conditional Object Function

Updated: Feb 8

When automating UI tests, navigation menus that expand and collapse dynamically are a common source of flaky tests. If a menu group is already expanded, clicking it again may collapse it - hiding the submenu items and causing test failures.


This reference explains a clean, reusable Cypress pattern for safely navigating collapsible menus by ensuring a menu group is expanded only when necessary.



The Problem: Collapsible Menus Cause Flaky Tests


Consider the following navigation structure:

  • Forms

    • Form Layouts

    • Date Picker

  • Modal & Overlays

    • Toastr

    • Tooltip


Clicking Forms or Modal & Overlays toggles the menu state:

  • If collapsed → it expands

  • If expanded → it collapses


Initial Navigation Page Object (Problematic)

Why This Is a Problem


This implementation assumes the menu group is always collapsed before clicking it.

In reality:

  • Another test may have already expanded the menu

  • Clicking again collapses it

  • The submenu item is no longer visible

  • Cypress fails because it can’t click a hidden element


This leads to intermittent failures - the worst kind of test bugs.


The Solution: Check Menu State Before Clicking


Most modern UI frameworks expose accessibility attributes such as:

We can leverage this attribute to:

  • Click the menu only if it is collapsed

  • Leave it alone if it’s already expanded


Reusable Helper Function

How This Works

  1. Locate the menu group link

    cy.contains('a', menuItem)

  2. Read its aria-expanded attribute

    invoke('attr', 'aria-expanded')

  3. Conditionally click

    • If aria-expanded="false" → click to expand

    • If aria-expanded="true" → do nothing


This approach makes the navigation idempotent: calling the function multiple times consistently ensures that the menu remains expanded.


Improved Navigation Page Object


 
 
bottom of page