¿Es posible seleccionar un elemento aleatorio dentro de eq() ? Tengo el siguiente caso de uso: hay varios menús desplegables con diferentes opciones desplegables. Quiero que Cypress abra el menú desplegable, obtenga la cantidad máxima de opciones desplegables y luego seleccione una opción aleatoria del conteo. Me gustaría evitar hacer esto con variables separadas, sino directamente de forma dinámica dentro del comando. Así es como se ve mi intento actual, pero no funciona:
cy.dropdownSelector().eq(0).click() cy.dropdownOptions().eq(Math.floor(Math.random() * cy.dropdownOptions().length)).click()Entonces, para generar un número aleatorio entre min (incluido) y max (incluido), debe usar esto:
Math.floor(Math.random() * (max - min + 1)) + minAsí que ahora su código de ciprés será:
cy.get('optionsselector') .its('length') .then((len) => { cy.get('optionsselector') .eq(Math.floor(Math.random() * ((len-1) - 0 + 1)) + 0) .click() })Tengo un comando para obtener un índice aleatorio usando lodash ( https://lodash.com/docs/4.17.15 ) y evitar repetir el índice si necesita repetir la prueba con otro nodo, debe proporcionar la longitud de la matriz y un array con las posiciones que ya han sido probadas.
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'); } }); }No hay necesidad de usar eq()
Puede usar el método de sample de Lodash que está integrado en Cypress. sample elegirá un artículo al azar de la colección.
Hace que la prueba sea más breve y clara:
cy.get('selector').then(options => { cy.get(Cypress._.sample(options)).click() })