1

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

FlawFull
  • 87
  • 9

3 Answers3

3

The general pattern for this would be as follows:

const element = Cypress.$('div.name:contains(Test 1)')
if (element.length > 0) {   
  ...

Make sure the DOM is stable when you run this code, there is no retry built in as there is with cy.contains()

If the code inside if() is creating the name, then maybe the logic would be

const element = Cypress.$('div.name:contains(Test 1)')
if (element.length === 0) {   
  // not found so create it
  ...
Fody
  • 23,754
  • 3
  • 20
  • 37
3

You can also do it like this

cy.get('div.name').then($div => {
  const found = $div.find(':contains("Test 1")')
  if (found.length === 0) {
    // create...
  }
})
1

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
  }
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • 1
    Thank you so much! This worked for me, although I changed .length > 0 to .length === 0 as I just needed to check if the element existed and do x if it didn't, I didn't need to do anything if it did. – FlawFull Jul 15 '22 at 07:59