'Cypress: How to know if element is visible or not in using If condition and xpath?

Cypress: How to know if element is visible or not in using If condition?

The answer of the above question works perfectly for CSS selectors. The answer is

cy.get("body").then($body => {
    if ($body.find("selector_for_your_button").length > 0) {   
    //evaluates as true if button exists at all
        cy.get("selector_for_your_button']").then($header => {
          if ($header.is(':visible')){
            //you get here only if button EXISTS and is VISIBLE
          } else {
            //you get here only if button EXISTS but is INVISIBLE
          }
        });
    } else {
       //you get here if the button DOESN'T EXIST
       assert.isOk('everything','everything is OK');
    }
});

I want to achieve something similar but for XPath. Can anyone help me?

Thank you in advance



Solution 1:[1]

With XPath you can use count()

cy.xpath(`count(//*[@class="${selector}"])`)
  .then(count => {
    if (count > 0) {
      cy.xpath(`//*[@class="${selector}"]`)  // repeat without count
        .click()
    } else {

    }
  })

But I think @jjhelguero's warning still applies. There isn't any retry with conditional testing, so you are losing the biggest advantage of Cypress - reducing flakiness in your tests.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1