FlawFull
FlawFull

Reputation: 157

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

Upvotes: 1

Views: 1503

Answers (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...
  }
})

Upvotes: 3

Alapan Das
Alapan Das

Reputation: 18650

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
  }
})

Upvotes: 1

Fody
Fody

Reputation: 31904

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
  ...

Upvotes: 3

Related Questions