How to Assert Element Does Not Exist in Cypress Tests
In Cypress, to assert that an element does not exist, use
cy.get(selector).should('not.exist'). This command waits and confirms the element is not found in the DOM, failing the test if it appears.Syntax
The basic syntax to assert an element does not exist is:
cy.get(selector): Finds the element by the CSS selector..should('not.exist'): Asserts the element is not present in the DOM.
javascript
cy.get('selector').should('not.exist')
Example
This example shows how to check that a button with the class .submit-btn does not exist on the page.
javascript
describe('Element absence test', () => { it('checks that the submit button does not exist', () => { cy.visit('https://example.cypress.io') cy.get('.submit-btn').should('not.exist') }) })
Output
Test passes if no element with class '.submit-btn' is found; fails if it exists.
Common Pitfalls
Common mistakes include:
- Using
cy.get()with.should('not.exist')on elements that are temporarily in the DOM but hidden, which can cause flaky tests. - Confusing
cy.get()withcy.find()orcy.contains()which behave differently. - Not waiting for the page or elements to load before asserting non-existence.
To avoid these, ensure the page state is stable before asserting and use cy.get() properly.
javascript
/* Wrong way: This fails if element is hidden but present */ cy.get('.hidden-element').should('not.exist') /* Right way: Use conditional checks or ensure element is removed */ cy.get('body').then($body => { if ($body.find('.hidden-element').length === 0) { // element does not exist } else { // element exists } })
Quick Reference
Summary tips for asserting element absence in Cypress:
- Use
cy.get(selector).should('not.exist')to check element absence. - Ensure the page is fully loaded before asserting.
- Remember
not.existchecks the DOM, not visibility. - For elements that might be hidden but present, use other strategies like checking CSS or conditional logic.
Key Takeaways
Use cy.get(selector).should('not.exist') to assert an element is not in the DOM.
Make sure the page and elements have loaded before checking for absence.
not.exist checks presence in the DOM, not visibility or display.
Avoid flaky tests by not confusing hidden elements with non-existent ones.
Use conditional logic if elements may be temporarily present but hidden.