简体   繁体   中英

function to return boolean to check if element exist in cypress

How can I write a function to return boolean to check if element exist on UI in cypress. I have follow code it seems to work fine until I hit one element that I can only get the element by cy.get('.I_am_selector') and when I use my function isElementExist it always return fasle because Cypress.$( .I_am_selector ).length == 0;

export function isElementExist(selector: string): boolean {
  try {
    return Cypress.$(`.${selector}`).length > 0;
  } catch (error) {
    return false;
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM