How to select nth item inside select element in cypress

半腔热情 提交于 2019-12-18 14:09:18

问题


say I have the HTML:

<select name="subject" data-testid="contact-us-subject-field">
  <option value="What is this regarding?">What is this regarding?</option>
  <option value="Partnerships">Partnerships</option>
  <option value="Careers">Careers</option>
  <option value="Press">Press</option>
  <option value="Other">Other</option>
</select>

Selecting an option with a known value, such as 'Careers' is as easy as:

cy.get('[data-testid="contact-us-subject-field"]').select('Careers');

How do I select the nth option in this field, regardless of its value?


回答1:


By using eq

cy.get('tbody>tr').eq(0)    // Yield first 'tr' in 'tbody'
cy.get('ul>li').eq(4)       // Yield fifth 'li' in 'ul'



回答2:


In the particular context of selecting the nth option, this may be appropriate:

cy.get('select[name=subject] > option')
  .eq(3)
  .then(element => cy.get('select[name=subject]').select(element.val()))



回答3:


Based on solution from Miguel Rueda, but using prevSubject option:

Cypress.Commands.add(
  'selectNth',
  { prevSubject: 'element' },
  (subject, pos) => {
    cy.wrap(subject)
      .children('option')
      .eq(pos)
      .then(e => {
        cy.wrap(subject).select(e.val())
      })
  }
)

Usage:

cy.get('[name=assignedTo]').selectNth(2)

Explanation:

  • Using children('option') and .eq(pos) traverse children of select to specific element.
  • Call select method with value of selected element.



回答4:


I had the same problem and solved it by creating a custom cypress command. No as pretty as I would like, but it did the job.

Cypress.Commands.add("selectNth", (select, pos) => {
  cy.get(`${select} option +option`)
    .eq(pos)
    .then( e => {
       cy.get(select)
         .select(e.val())
    })
})

then I used in the test as such

    cy.viewport(375, 667)
      .selectNth("customSelector", 3)

The option +option part was the only way I could find to get the full list of options inside a select and it's currently the bit of code i'm trying to work arround although it works fine.



来源:https://stackoverflow.com/questions/50750956/how-to-select-nth-item-inside-select-element-in-cypress

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!