I want to check that a piece of text either does not even exist in the DOM or that if it exists, it is invisible.
cy.contains(text).should("not.visible)
handles the second case, cy.contains(text).should("not.exist")
the first, but either of them fails in the case of the other.
Before trying a conditional solution, have a read through this paragraph https://docs.cypress.io/guides/core-concepts/conditional-testing#Error-Recovery
This is a feature that they intentionally made not available
Enabling this would mean that for every single command, it would recover from errors, but only after each applicable command timeout was reached. Since timeouts start at 4 seconds (and exceed from there), this means that it would only fail after a long, long time.
every cy...should
has a built-in timeout, so if you have multiple your wait time would stack.
Alternatively, you can use this trick (at your peril 😉).
cy.get("body").then(($body) => {
if ($body.find(":contains(texta)").length > 0) {
cy.contains("texta").should("not.be.visible");
} else {
cy.contains("texta").should("not.exist");
}
});
cy.get("body").then(($body) => {
will get the copy of body(DOM) in the current state and make it available for synchronous querying using jQuery. With jQuery we can determine synchronously whether an element contains the text
string with $body.find(":contains(text)")
using the result's length you can make a condition that will then fire off cypress' asynchronous assertions.