如何在赛普拉斯中测试下拉列表 (select) 框中的所有选项?

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

我们如何 select 全部 options 来自普通下拉列表框并使用 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')
   });
});

我建议测试可能看起来像这样

cy.get('#cars_list option').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})

cy.get('#cars_list').children('option').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})

cy.get('#cars_list').find('option').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['volvo', 'saab', 'mercedes', 'audi'])
})

使用 cy.get() 选择多个子元素,然后使用 [...options] 展开它们,使用 .map(o => o.value) 映射到它们的值并使用深度等于来比较数组。

我没有对此进行测试,因此代码可能需要一些调整。