Cypress cy.get()
has retry built in, so if an element is loading or animating the command will eventually grab the element.
But the jQuery equivalent Cypress.$(
.${selector})
does not have retry. You could try to build some polling in your function, but it's a lot of work and why is there not a cy.maybe(selector)
built into Cypress?
Cypress tests work best if you know what elements are present, there's a lot of documentation around it, but there's always edge cases.
The only way I've seen to do this is here How can manage the application flow, if the element xpath is not present, using the cypress-xpath add-on and the count()
function.
cy.xpath(`count(//${element}[@class="${selector}"])`) // ok with async content
.then(count => {
const selector = count ? selector : defaultSelector;
You may be looking for the jQuery OR Selector which allows you to supply a default selector after the comma.
If the DOM is like this
<div class="pick-me">one</div>
<div class="or-me">two</div>
This test will fetch div.pick-me
cy.get('.pick-me, .or-me') // jQuery OR selector
.eq(0) // in case both match, take first
.should('have.class', 'pick-me'); // first selector is used
But if the DOM doesn't have the first class,
<div class="dont-pick-me">one</div>
<div class="or-me">two</div>
the command will return the default selector
cy.get('.pick-me, .or-me') // jQuery OR selector
.eq(0) // in case both match, take first
.should('have.class', 'or-me'); // default selector is used