How can we select all options
from a normal drop-down list box and verify them using Cypress?
<select id="cars_list">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
//The below test can check only for one option, how can we verify the rest?
describe("Select all values from drop down list", function() {
it("Cypress test and verify all options", function() {
cy.visit("Https://sometestingsite")
cy.get('#cars_list').then(function($select){
$select.val('volvo')
})
cy.get('select').should('have.value', 'volvo')
});
});
How can we select all options
from a normal drop-down list box and verify them using Cypress?
<select id="cars_list">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
//The below test can check only for one option, how can we verify the rest?
describe("Select all values from drop down list", function() {
it("Cypress test and verify all options", function() {
cy.visit("Https://sometestingsite.com")
cy.get('#cars_list').then(function($select){
$select.val('volvo')
})
cy.get('select').should('have.value', 'volvo')
});
});
Share
Improve this question
edited Nov 4, 2021 at 16:48
M. Justin
21.2k10 gold badges127 silver badges161 bronze badges
asked Dec 3, 2018 at 21:03
soccerwaysoccerway
12k23 gold badges80 silver badges159 bronze badges
6
|
Show 1 more comment
1 Answer
Reset to default 16I would suggest the test might look like this
cy.get('#cars_list option').then(options => {
const actual = [...options].map(o => o.value)
expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})
OR
cy.get('#cars_list').children('option').then(options => {
const actual = [...options].map(o => o.value)
expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})
OR
cy.get('#cars_list').find('option').then(options => {
const actual = [...options].map(o => o.value)
expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})
Selecting multiple child elements with cy.get()
, then unwrapping them with [...options]
, mapping to their value with .map(o => o.value)
and using a deep equal to compare arrays.
I have not tested this, so the code may need some tweaking.
option list
has expected values. Some one down voted though, don't know why ? – soccerway Commented Dec 3, 2018 at 21:41cy.get('#cars_list').its('options').then(options => ...)
. – user9161752 Commented Dec 3, 2018 at 21:45cy.get('#cars_list option').then(options => ...)
suits? – user9161752 Commented Dec 3, 2018 at 21:50