Select 包含重复值的下拉列表中的值

Select a value from dropdown containing duplicate values

嗨,我是 Cypress 的新手,正在尝试自动化这个场景 -

我有一个像这样的具有重复值的下拉列表:

  <select name="cars" id="cars">
    <option value="volvo">Volvo</option>
    <option value="volvo">Volvo</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>

现在我要 select 出现在列表中的第二个沃尔沃。我尝试过的事情:

cy.get('select#cars').select('Volvo') //This selects the first Volvo

编辑:现在基于上面的selection,网页上显示了一个新元素,我正在检查该元素的内部文本-

cy.get('selector', {timeout: 8000}).should('have.text', some text)

查看源代码,.select() 命令将 inputchange 事件分派到所选选项。

您可以“手动”执行相同的操作selecting

cy.get('option').eq(1).then($option => {

  const input = new Event('input', { bubbles: true, cancelable: false })
  $option.get(0).dispatchEvent(input)

  const change = document.createEvent('HTMLEvents')
  change.initEvent('change', true, false)
  $options.get(0).dispatchEvent(change)
})

参考:/driver/src/cy/commands/actions/select.js


这也有效

cy.get('option').eq(1)
  .trigger('input', { force: true })   
  .trigger('change', { force: true })  
  // force because select is not open so option isn't visible

虽然任何一种方式都会触发事件,但它不会 select 选项。

这样就可以了,

cy.get('option').eq(1)
  .trigger('input', { force: true }) 
  .trigger('change', { force: true })
  .then($option => {
    cy.get('select').then($select => $select.val($option.val()))
  })