How to select nth item inside select element in cypress

前端 未结 7 1092
梦毁少年i
梦毁少年i 2020-12-29 18:16

say I have the HTML:


                        
    
提交评论

  • 2020-12-29 18:56

    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.

    0 讨论(0)
  • 2020-12-29 19:06

    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()))
    
    0 讨论(0)
  • 2020-12-29 19:06

    since the working answers are using then anyways, eq or something fancier is redundant with array indexing...

    // to click on the 1st button
    cy.get('button').then($elements => {cy.wrap($elements[0]).click();});
    // to click on the 4th tr
    cy.get('tr').then($elements => {cy.wrap($elements[3]).click();}); 
    // to click on the last div:
    cy.get('div').then($elements => {cy.wrap($elements[$elements.length - 1]).click();});
    
    0 讨论(0)
  • 2020-12-29 19:11

    Capture all the elements in the drop-down using a selector. Get the length. Use math.random() to randomly get a number. Select the option at the index.

    cy.get("ul > li").as("options")
    cy
    .get("@options")
    .its('length')
    .then(len => Math.floor(Math.random() * Math.floor(len)))
    .then((index) => {
    cy.get("@options").eq(index).click()
    })
    
    0 讨论(0)
  • 2020-12-29 19:14

    Update

    As pointed out by @dpstree in the comments, this doesn't answer the original question. Please see more recent answers for a complete solution.

    Original

    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'
    
    0 讨论(0)
  • 提交回复
    热议问题