soccerway
soccerway

Reputation: 11991

How can all options from a drop-down list (select) box be tested in Cypress?

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')
   });
});

Upvotes: 10

Views: 16018

Answers (1)

user9161752
user9161752

Reputation:

I 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.

Upvotes: 16

Related Questions