'Cypress: possible to select random element with eq() dynamically?

is it possible to select a random element within the eq()? I have the following use case: There are several dropdowns with different dropdown options. I want Cypress to open the dropdown, get the max number of dropdown options and then select a random option from the count. I would like to avoid doing this with separate variables but rather directly dynamically within the command. This is what my current attempt looks like but it doesn't work:

cy.dropdownSelector().eq(0).click()
cy.dropdownOptions().eq(Math.floor(Math.random() * cy.dropdownOptions().length)).click()


Solution 1:[1]

I have a command to get a random index using lodash (https://lodash.com/docs/4.17.15) and avoid repeating index if you need to repeat the test wit another node, you have to provide the length of the array and an array with the positions that have already been tested.

const _ = require('lodash');

/**
 * Calculates a random position in a given array
 * @param  {Number} length array length
 * @param  {Array} positionsTested positions in the array that have 
already been tested
*/
Cypress.Commands.add('getRandomPosition', (length, positionsTested) => {
  if (positionsTested.length >= length) {
    return cy.wrap(null);
}
const i = _.random(length - 1);
return cy.wrap((_.find(positionsTested, i)) ? 
  cy.getRandomPosition(length, positionsTested) : i);
});

// usage
cy.dropdownSelector().then((elements) => {
  doTheTest([], elements);
});

function doTheTest (positionsTested, elements) {
  cy.getRandomPosition(elements.length, positionsTested).then((index) => {
    if (index !== null) {
      positionsTested.push(index);
      const selectedElement = elements[index];
      if (suitableToTest(selectedElement)) {
        // do something with the element
      } else {
        doTheTest(positionsTested, elements);
      }
    } else {
      cy.log('not enough elements to test');
    }
  });
}

Solution 2:[2]

There is no need to use eq()

You can use the sample method from Lodash which is baked in in Cypress. sample will pick a random item from the collection.

It makes the test shorter and more clear:

cy.get('selector').then(options => {
  cy.get(Cypress._.sample(options)).click()
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VerĂ²nica Jandrew
Solution 2 tlolkema