Search code examples
javascriptselenium-webdrivercypress

How to check if element exists using Cypress.io


How to check if element is present or not, so that certain steps can be performed if element is present. Else certain different steps can be performed if element is not present.

I tried something like below but it didn't work:

Cypress.Commands.add('deleteSometheingFunction', () => {
  cy.get('body').then($body => {
    if ($body.find(selectors.ruleCard).length) {
      let count = 0;
      cy.get(selectors.ruleCard)
        .each(() => count++)
        .then(() => {
          while (count-- > 0) {
            cy.get('body')
            // ...
            // ...
          }
        });
    }
  });
  });

I am looking for a simple solution, which can be incorporated with simple javascript if else block or then() section of the promise

Something similar to Webdriver protocol's below implementions:

  1. driver.findElements(By.yourLocator).size() > 0
  2. check for presenece of element in wait

Kindly advise. Thanks


Solution

  • cypress all steps are async ,, so that you should make common function in commands file or page object file,,..

        export function checkIfEleExists(ele){
        return new Promise((resolve,reject)=>{
            /// here if  ele exists or not
            cy.get('body').find( ele ).its('length').then(res=>{
                if(res > 0){
                    //// do task that you want to perform
                    cy.get(ele).select('100').wait(2000);
                    resolve();
                }else{
                    reject();
                }
            });
        })
    }
    
    
    // here check if select[aria-label="rows per page"] exists
    cy.checkIfEleExists('select[aria-label="rows per page"]')
    .then(e=>{
            //// now do what if that element is in ,,..
            })
    .catch(e=>{
        ////// if not exists...
        })