Reputation: 2693
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.
Upvotes: 1
Views: 2859
Reputation: 32044
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())
})
Upvotes: 5
Reputation: 18626
You can do something like this. First get the number of options and then using that select the last item.
cy.get('select')
.find('option')
.its('length')
.then((len) => {
cy.get('select').select(len - 1)
})
Upvotes: 2