conditional-statementscypresscypress-conditional-testing

cypress conditional testing with labels/text


How do you do conditional testing in cypress with labels? For example: I want to know if there is the "ole" written in between the span:

<div>
  <span role="test">ole</span> 
</div>

Now with the attribute this is well documented and works nicely:

cy.get('div').then((ol) => {
   if(ol.find('span[role="test"]').length){
       // do something
   } else {
       // do something else
   }
})

But with labels??

cy.get('div').then((ol) => {
   if(ol.contains('ole').length){  // this does not work!
       // do something
   } else {
       // do something else
   }
})

Solution

  • The equivalent for text in the element is .text().

    Technically it's only a label if it's labeling something, but .text() applies to anything between the opening and closing tags.

    cy.get('div').then((ol) => {
      if (ol.text() === 'ole') {  
      
      } else {
      
      }
    })