How to check if element exists using Cypress.io

后端 未结 4 532
不知归路
不知归路 2020-12-01 16:00

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 pres

4条回答
  •  广开言路
    2020-12-01 17:03

    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

提交回复
热议问题