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

How to test for an element not existing using Cypress?

1个答案

1

When using Cypress for automated testing, ensuring that certain elements do not exist on the page is also a critical aspect. This helps verify the correctness of the page, especially after performing delete or hide operations. Below are some steps and examples illustrating how to test for non-existing elements using Cypress:

1. Using .should('not.exist')

The most straightforward approach is to use the .should('not.exist') assertion to check if an element does not exist. This assertion waits for Cypress's default timeout; if the element is not found within this time, the test passes.

Example code: Suppose we have a feature that deletes a list item; we can confirm the successful deletion as follows:

javascript
// Assuming each list item has a specific test ID cy.get('[data-testid="item-123"]').within(() => { cy.get('.delete-button').click(); }); // Verify that the list item no longer exists cy.get('[data-testid="item-123"]').should('not.exist');

2. Using .not()

Another method is to use the .not() function with selectors to verify that an element does not possess specific conditions. This is typically used to check if an element lacks certain CSS classes or attributes.

Example code: Suppose we want to confirm that a button no longer has the active class after an operation:

javascript
cy.get('.button').click(); cy.get('.button').should('not.have.class', 'active');

3. Combining .find() and .should('not.exist')

If you need to check for the absence of child elements within a parent element, you can combine .find() and .should('not.exist').

Example code: Suppose we need to test that after clicking a dropdown menu, its options are correctly removed:

javascript
cy.get('.dropdown').click(); cy.get('.dropdown-menu').find('.option-5').should('not.exist');

4. Using .and('not.have.descendants', 'selector')

This method can be used to confirm that an element has no descendant elements matching a specific selector.

Example code: Testing that a container element does not contain any <li> child items:

javascript
cy.get('.container').should('not.have.descendants', 'li');

Summary

The following are several methods to test for non-existing elements in Cypress. In practical testing, the choice of the most suitable method depends on the specific test scenarios and requirements. It is important to understand the differences between these methods and how they contribute to ensuring the correctness of the page UI and the completeness of functionality.

2024年6月29日 12:07 回复

你的答案