Cypress: Test if element does not exist
Testing for an element's non-existence in Cypress is achieved using the .should('not.exist')
assertion. It's a direct confirmation that the element is entirely absent from the DOM.
This is a purposely targeted command for affirming that the specified element (in this case #element
) is not lurking anywhere on the web page.
Conquering async operations
An uphill battle with asynchronous operations, such as perceived server responses, is ensuring your assertions march in after the operations have taken their bow.
Consider this as fitting a synchronized dance, where cy.wait()
with proper aliases ensures your assertion only treads the stage when the asynchronous encore is over.
Conan the Invisible vs Miss Non-Existent
Much like the pole-apart genres of a meticulously planned mystery and a straightforward horror, .should('not.exist')
and .should('not.be.visible')
cater to different territories in testing. While not.exist
unearths the fact that an element is nowhere on the DOM island, not.be.visible
blares out that a technically present element has chosen to remain incognito.
When the intent is to unravel the mystery of an element's evaporation from the layout, .should('not.exist')
is your Holmes. Resort to .should('not.be.visible')
when hunting for intentionally concealed or shadowy elements.
Unveiling the hidden text fractals
Should you cross paths with situations demanding testing the absence of elements too craftily elusive to be nabbed with a clean selector, like text for instance, harness the power of cy.contains()
tamed with a .should('not.exist')
.
Work cy.contains()
with caution while testing non-existence as it might be prone to trip on false positives if your target text is vacationing elsewhere on the DOM island.
Following the breadcrumbs of user actions
validating an element's absence after user actions akin to checkbox clicks, it's crucial that your assertion only knocks the DOM's door once the action's repercussions have been reflected.
Enforce the Code of Conduct proclaiming that actions must be concluded before the assertions begin their investigation. Tools like cy.wait()
or cy.then()
can be invaluable sheriffs in mitigating any wild West scenarios of transition states or animations prior to checking the absence of an element.
Was this article helpful?