How do I wait for an element to disappear in Cypress?
Waiting for elements to disappear in Cypress is a common testing requirement that can be achieved through multiple approaches. This is particularly useful when handling asynchronous events, such as the disappearance of loading indicators, the closing of pop-ups, or updates to element states.Method 1: UsingThe most straightforward approach is to use the assertion. This method continuously checks for the element's absence until it no longer exists in the DOM. For example, to verify if a loading indicator disappears, you can write:Here, first attempts to locate the element with the class , and ensures it remains absent until the DOM no longer contains it.Method 2: UsingIf the element persists in the DOM but becomes invisible (e.g., via CSS properties like or ), use . This is ideal for elements hidden through styling. For instance:This code verifies that a modal window element is no longer visible.Method 3: Combining with AssertionsWhen you need to enforce a specific duration for state changes, combine with assertions:Use this approach cautiously, as fixed wait times can introduce instability in test results, especially under varying network conditions or system loads.Method 4: Using 's OptionCypress allows specifying a within , enabling explicit waiting during element retrieval:This code continuously checks for the notification element within 10 seconds until it disappears.Example ScenarioConsider a shopping cart application where a 'Success' message appears after adding an item and automatically vanishes after a few seconds. Your test must confirm this message correctly disappears:This test simulates user interaction, validates the message's appearance, and ensures it vanishes as expected, confirming the UI behaves correctly.