Check if element exists or not in cypress without getting error

I was testing a select dropdown, where if the option exists I had to select that otherwise I had to create that option.

And while testing it, I was facing a bug where when I was looking to check existence of an element using .should('exist'), cypress was throwing an error because the element was not there in the DOM.

cy
.findByRole('option')
.contains('prashant')
.should('exist')
.then(($el) => {
  if($el.length){
    //do something
  }else{
    // do something else
  }
})

I tried with multiple ways like checking with the .contains(text) method directly, but none of them worked.

cy
.contains('prashant')
.should('exist')
.then(($el) => {
  if($el.length){
    //do something
  }else{
    // do something else
  }
})

As a workaround, I tried something different. I used the parent selector method, where I set the data test ID on the component and then used that to find the component.

cy.get('[data-cy="to-list-select"]').then(($el) => {
   if ($el.find('[role="option"]').length > 0) {
      // If the "Add list" button is not visible, it means a match exists, so click on the list item
      $el.find('[role="option"]').first().click();
   } else {
      // If list does not exist, create a new list
      cy.findByRole('button', { name: 'Add to list' }).click();
      cy.findByRole('button', { name: 'Create' }).click();
   }
});

This provided more granular control, as we got the parent element (Select Dropdown) and then searched for options inside it which was under our control and prevented from error occurrence.