赛普拉斯:可以使用 eq() 动态 select 随机元素吗?

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

是否可以 select eq() 中的随机元素? 我有以下用例: 有几个具有不同下拉选项的下拉菜单。 我希望赛普拉斯打开下拉菜单,获取最大数量的下拉选项,然后 select 从计数中随机选择一个选项。 我想避免使用单独的变量来执行此操作,而是直接在命令中动态执行。这是我目前的尝试,但它不起作用:

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

所以要生成一个介于最小值(包括)和最大值(包括)之间的随机数,你必须使用这个:

Math.floor(Math.random() * (max - min + 1)) + min

所以现在您的赛普拉斯代码将是:

cy.get('optionsselector')
  .its('length')
  .then((len) => {
    cy.get('optionsselector')
      .eq(Math.floor(Math.random() * ((len-1) - 0 + 1)) + 0)
      .click()
  })

我有一个使用 lodash (https://lodash.com/docs/4.17.15) 获取随机索引的命令,如果您需要在另一个节点上重复测试,请避免重复索引,您必须提供数组的长度和一个数组与已经测试过的位置。

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');
    }
  });
}

不需要使用eq()

您可以使用 Lodash 中的 sample 方法,该方法内置于 Cypress 中。 sample 将从 collection 中随机选择一个项目。

它使测试更短更清晰:

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