selectcypressdynamic-content

Cypress select last option in dropdown


I have a dynamically generated dropdown with normal structure as:

<select>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
etc.
</select>

It is kind of pagination and I don't know how many items will be in the table and don't want to calculate how many options with which numbers will be in dropdown according to item count.

What I want to achieve with Cypress is simply always select the last option.

I know I can select any option by name or value, e.g. cy.get('select').select('10')

Also with index: cy.get('select').select(0)

But I don't know the last index.

I also tried select().last() but this doesn't work, as select must not be empty.


Solution

  • If your options are dynamic, you should ensure the list is populated before selecting

    cy.get('select option')
      .should('have.length.gt', 0)
    
    cy.get('select option')
      .last()
      .then($lastOption => {
        cy.get('select').select($lastOption.text())
      })