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")
}
2
Answers
So, certain Cypress commands (inlcudes
cy.get()
contain implicit assertions – meaning that Cypress will fail a test if the implicit assertion is not met. In this case, ifcy.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 thediv
element using JQuery functions.To pass the assertion to
if()
changecy.get()
toCypress.$()
.cy.get()
is a wrapper aroundCypress.$()
that retries until timeout then fails.Cypress.$()
just returns a jQuery object which haslength === 0
if it fails, but in either case the test continues.Make sure the page has finish loading (no fetch not yet responded) before running any
if()
condition.