Selecting cypress elements that do not contain text with Cypress

Viewed 1869

I am working on a test which runs into a dropdown with invalid selections. The dropdown does not disable these, you can click them, they simply read "unavailable" for the product.

<select readonly="" class="size-selector">
  <option value="">Size</option>
  <option value="XS">XS</option>
  <option value="S">S - Unavailable</option>
  <option value="M">M - Unavailable</option>
  <option value="L">L</option>
  <option value="XL">XL</option>
</select>

I want to be able to select the first option after Size which does not contain the text "Unavailable".

2 Answers

Cypress provides .filter() and the opposite .not() to filter lists.

cy.get('option')
  .not(':contains("Unavailable")')      // exclude Unavailable
  .not(':contains("Size")')             // exclude list header
  //.not('[value=""]')                  // alternative way to exclude list header
  .eq(0)                                // take the first
  .invoke('text')                       // get the text
  .then(firstAvailableOption => {
    cy.get('select.size-selector')
      .select(firstAvailableOption)     // use text to select option
  })

cy.get('select.size-selector')
  .invoke('val')
  .should('eq', 'XS')

You can do something like this: You loop through the options fields in your drop down using each(). Now check for the inner text for each of the options using text() jquery method. Once you find the element, use cy.select() to select the element.

cy.get('select.size-selector option').each(($ele) => {
    if (!($ele.text().includes('Unavailable') || $ele.text().includes('Size'))) {
        cy.get('select.size-selector').select($ele.text())
        return false; // Needed to break each loops in Cypress
    }
})
Related