【问题标题】:How to get a random item from an array in Cypress?如何从赛普拉斯的数组中获取随机项?
【发布时间】:2019-08-22 19:52:41
【问题描述】:

我正在尝试编写一个Cypress 测试,该测试从每页的每组5 问题中随机选择一个button 答案。

我正在尝试通过以编程方式在1- 5 之间选择一个数字并单击一个来实现此目的。可以从JavaScript 中的array 中获取随机项目,那么如何在Cypress 中执行此操作?

这是我正在使用的array 示例::

var myArray = ["Apples", "Bananas", "Pears"];
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];

由于Cypress 仍处于起步阶段,我很难找到有关如何设置条件语句的示例。根据我对Cypress中变量使用的理解,如果变量可见,则无需定义即可访问。

另外,我在提出适当的条件语句以随机选择一个单选按钮时遇到问题,其中问题会根据每页的每个 5 问题随机化 3-5 可见答案。

it('selects random radio buttons',() => {           
cy.get('@mat-radio-group')
     .children() 
     .each(($matRadioGroup) => {
         cy.get($matRadioGroup).children()
            if($matRadioGroup.children <= 5) {
                   .random function?
                   .click()
            }
        })

// This code clicks through all of the buttons on the page and leaves selected the last button for every question regardless of the randomizing visible answers (Does not randomize the button selection)

cy.get('@mat-radio-group')
   .children() 
   .each(($matRadioGroup) => {
     cy.get($matRadioGroup)
         .children()
         .eq(0)
         .click()

应该有一种方法可以做到这一点,而无需在赛普拉斯中使用 if 语句。我是一个初学者开发者,所以任何提示或建议将不胜感激!

【问题讨论】:

    标签: javascript arrays cypress


    【解决方案1】:

    只是一些其他的想法。由于它们都是无线电buttons,因此无需创建array 并随机选择其中一个array

    您还可以在04 之间创建一个随机数。然后结合eq()的用法。

    您已经了解了如何随机选择一个数组项,就像您可以随机选择一个数字一样: Math.floor(Math.random() * 5).

    因此,如果我采用您的最后一部分代码并添加随机选择,它看起来像这样:

    cy.get('@mat-radio-group')
       .children() 
       .each(($matRadioGroup) => {
         cy.get($matRadioGroup)
             .children()
             .eq(Math.floor(Math.random() * 5))
             .click()
    

    【讨论】:

    • 感谢您的回复。使用这种方式时,我得到 CypressError: Timed out retrying: E​​xpected to find element: '1',但从未找到它。从元素查询:。在额外运行时,该元素编号确实会更改/随机化。我相信这个单选按钮组还包含字符串文本问题,所以也许这就是问题所在?
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多