I am trying to pass an assertion to if condition and execute a logic when the condition is met and another logic when condition is failed.
Since the test is failing on failure of assertion i am not able to achieve the desired result.
I tried the following...
if(cy.get("div").length \> 0) {
cy.log("print this")
} else {
cy.log("print this")
}
or
if(cy.get("div").should('have.length.greaterThan', 0) {
cy.log("print this")
} else {
cy.log("print this")
}
So, certain Cypress commands (inlcuding cy.get()
) contain implicit assertions - meaning that Cypress will fail a test if the implicit assertion is not met. In this case, if cy.get()
fails to find an element, that fails the implicit assertion, and the test will fail.
Additionally, Cypress commands will yield objects that are of type Chainable<T>
, meaning they don't yield traditional objects that can have .length
appended to them.
Instead of using cy.get('div')
, we get the parent element and search for the div
element using JQuery functions.
cy.get('body') // get the parent of the div
.then(($body) => { // then unwraps the Chainable<JQueryHTMLElement> Object
if ($body.find('div').length) { // We can use JQuery commands directly on the yielded $body element
// code if `div` has a length greater than 0
} else {
// code if `div` has a length of 0
}
});