乐闻世界logo
搜索文章和话题

How do I wait for an element to disappear in Cypress?

1个答案

1

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: Using .should('not.exist')

The most straightforward approach is to use the .should('not.exist') 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:

javascript
cy.get('.loading-indicator').should('not.exist');

Here, cy.get() first attempts to locate the element with the class loading-indicator, and .should('not.exist') ensures it remains absent until the DOM no longer contains it.

Method 2: Using .should('not.be.visible')

If the element persists in the DOM but becomes invisible (e.g., via CSS properties like display: none or visibility: hidden), use .should('not.be.visible'). This is ideal for elements hidden through styling. For instance:

javascript
cy.get('.modal').should('not.be.visible');

This code verifies that a modal window element is no longer visible.

Method 3: Combining cy.wait() with Assertions

When you need to enforce a specific duration for state changes, combine cy.wait() with assertions:

javascript
cy.wait(1000); // Wait for 1000 milliseconds cy.get('.alert').should('not.exist');

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 cy.get()'s timeout Option

Cypress allows specifying a timeout within cy.get(), enabling explicit waiting during element retrieval:

javascript
cy.get('.notification', { timeout: 10000 }).should('not.exist');

This code continuously checks for the notification element within 10 seconds until it disappears.

Example Scenario

Consider 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:

javascript
describe('Shopping Cart Feature Test', () => { it('After adding an item, the success message should automatically disappear', () => { // Assume the add-to-cart button has an ID of 'add-to-cart' cy.get('#add-to-cart').click(); // Verify the message appears cy.get('.success-message').should('be.visible'); // Wait and verify the message disappears cy.get('.success-message').should('not.exist'); }); });

This test simulates user interaction, validates the message's appearance, and ensures it vanishes as expected, confirming the UI behaves correctly.

2024年6月29日 12:07 回复

你的答案