How to check if element exists using Cypress.io

后端 未结 4 500
不知归路
不知归路 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 16:48

    Using async/await gives a clean syntax:

    const $el = await cy.find("selector")
    if ($el.length > 0) {
      ...
    

    More info here: https://medium.com/@NicholasBoll/cypress-io-using-async-and-await-4034e9bab207

    0 讨论(0)
  • 2020-12-01 16:51

    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})
            }
        })
    
    0 讨论(0)
  • 2020-12-01 16:57

    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...
        })
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题