Ashley
Ashley

Reputation: 157

How do I click through all the options in the dropdown in Cypress?

I want to click through the countries in the dropdown and then get the number of users in each. When I click on the country in the dropdown, it displays the number of users. I think I can loop through and then get them, but not sure how to do it. can I use for loop and use the index to click through the elements or create an array with the country names and use them to click through?

<div class="dropdown-menu open" style="max-height: 222px; overflow: hidden;">
  <ul class="dropdown-menu inner" role="menu" aria-label="Dropdown" style="max-height: 222px; overflow-y: auto;">
    <li data-original-index="0" class="">
      <a tabindex="0" class="" style="" data-tokens="null">
        <span class="text">All countries </span>
        <span class="glyphicon glyphicon-ok check-mark"></span></a></li>
    <li data-original-index="1" class="">
      <a tabindex="0" class="" style="" data-tokens="null">
        <span class="text">Belgium</span>
        <span class="glyphicon glyphicon-ok check-mark"></span></a></li>
    <li data-original-index="2">
      <a tabindex="0" class="" style="" data-tokens="null">
        <span class="text">Sweden</span>
        <span class="glyphicon glyphicon-ok check-mark"></span></a></li>
    <li data-original-index="3">
      <a tabindex="0" class="" style="" data-tokens="null">
        <span class="text">Hungary</span>
        <span class="glyphicon glyphicon-ok check-mark"></span></a></li>
    <li data-original-index="4">
      <a tabindex="0" class="" style="" data-tokens="null">
        <span class="text">Germany</span>
        <span class="glyphicon glyphicon-ok check-mark"></span></a></li>
    </ul></div>

Upvotes: 0

Views: 1693

Answers (1)

Nipuna Madusanka
Nipuna Madusanka

Reputation: 196

Please try following way to get element collection and iterate through the wrapped jQuery elements. Please refer Cypress Iterate over an array of DOM elements for further details. I'm not sure whether you can find unique class or id above the DOM that you have provided, if exists please alter the 'div.dropdown-menu.open > ul > li> a > span.text' css selector accordingly.

When you add class name in to css selector, if the class name contains spaces "ex: class name", then replace the "space" with "." (ex: class.name). This will looks like ('div.class.name > div.dropdown-menu.open > ul > li> a > span.text')

cy
  .get('div.dropdown-menu.open > ul > li> a > span.text')  //This will create countries element collection
  .each(($el, index, $list) => {
    //<<Add here the drop down expand element click action>>
    // $el is a wrapped jQuery element, wrap this element so we can use cypress commands on it
    cy.wrap($el).click()
  })

Upvotes: 1

Related Questions