cypresscypress-conditional-testing

Cypress - How to use if statement with contains


so I have to use cy.contains to find the element I want, but all I can find online is how to use if() with cy.find or cy.get if there a way to do this with contains?

Example code:

if(cy.contains('div.name', 'Test 1').length > 0) {   
            //Type in name
            cy.get('input.newName').click().type('Test 1'); 
            cy.wait(2000);
            //Click Add Name
            cy.get('div.createNewName> a').click();
            cy.wait(2000);
        }

What I am trying to do there is:

if(Name doesnt exist){
    Create it
}

I'm not sure if I have explained myself too well, if any more clarifications are needed feel free to ask


Solution

  • You can also do like this:

    cy.get('body').then(($body) => {
      if ($body.find('div.name:contains("Test 1")').length > 0) {
        //Element Found
      } else {
        //Element not found
      }
    })