Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Cypress select() When Select Contains Duplicate Values

I need to select a value in a select. The select is a list of countries, displaying their names, with a two-letter country code as the value for each option. We surface the most selected countries to the top, while also leaving them in their alphabetical position. This means the items surfaced to the top are repeated twice.

<select>
  <option value="gb">UK</option>
  <option value="us">USA</option>
  <option value="af">Afganistan</option>
  <option value="ai">Aland Islands</option>
  ...
  <option value="us">USA</option>
  <option value="gb">UK</option>
  ...
</select>

I'm selecting a value like this:

cy.getSelect().select('gb')

However, this raises an error:

CypressError: Timed out retrying: cy.select() matched more than one option by value or text: gb

This makes sense as the value for 'UK' is gb and it appears at the top of the list and within the list in its alphabetical position.

How can I tell Cypress to ignore the duplicate value and select the first match?

Note that I cannot guarantee the index of any country and that I have lots of other tests that select different countries. I need a way to tell Cypress to select the first match.

like image 874
Undistraction Avatar asked Sep 18 '25 09:09

Undistraction


2 Answers

You can try dropping down to jQuery/JavaScript to manually set the field:

cy.get('select').then($country => {$country.val("gb")})

The $country above should be a jQuery object wrapping the html that you selected.

See: https://docs.cypress.io/api/commands/then.html#Syntax

like image 131
jpvantuyl Avatar answered Sep 20 '25 22:09

jpvantuyl


Here are a couple sources to look through: https://docs.cypress.io/api/commands/select.html#Text-Content & https://docs.cypress.io/api/commands/eq.html#Syntax

What I would recommend trying would be along the lines of this: cy.get('select').select('gb').eq(0) or cy.get('select').select('gb').first()

Either of these options will grab the first item if duplicates are found. Other things you can do with eq() are eq(-1) for the last item, or eq(2) for the third item (base zero) and so on.

Edit: use cy.get('select') instead of cy.getSelect();

like image 30
Porter Lyman Avatar answered Sep 20 '25 21:09

Porter Lyman