How to check if element exists using Cypress.io

两盒软妹~` 提交于 2019-12-22 06:59:06

问题


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) Or check for presenece of element in wait

Kindly advise. Thanks


回答1:


it has been questioned before: Conditional statement in cypress

Thus you can basically try this:

cy.get('header').then(($a) => { 
        if ($a.text().includes('Account')) {
            cy.contains('Account')
            .click({force:true})
        } else if ($a.text().includes('Sign')) { 
            cy.contains('Sign In')
            .click({force:true})  
        } else {
            cy.get('.navUser-item--account .navUser-action').click({force:true})
        }
    })



回答2:


I'll just add that if you decide to do if condition by checking the .length property of cy.find command, you need to respect the asynchronous nature of cypress.

Example: Following condition evaluates as false despite appDrawerOpener button exists

    if (cy.find("button[data-cy=appDrawerOpener]").length > 0)    //evaluates as false

But this one evaluates as true because $body variable is already resolved as you're in .then() part of the promise:

    cy.get("body").then($body => {
        if ($body.find("button[data-cy=appDrawerOpener]").length > 0) {   //evaluates as true
            cy.get("button[data-cy=appDrawerOpener]")
            .click();
        }
    });

Read more in Cypress documentation on conditional testing



来源:https://stackoverflow.com/questions/56145926/how-to-check-if-element-exists-using-cypress-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!