How to get a random item from an array in Cypress using Javascript

江枫思渺然 提交于 2021-01-29 13:03:49

问题


I am attempting to write a Cypress test that selects a random radio button answer from each group of 5 questions per page. I am trying to do this by having the code choose a number between 1-5 and clicking on one. It is possible to get a random item from an array in javascript, so how to do this in Cypress?

The Javascript array example that I am using is this:

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

Since Cypress is still in its infancy, I am having trouble finding examples on how to set up conditional statements. From what I understand of variable use in cypress, if the variable is visible, it can be accessed without the necessity of defining it in Cypress. Also, I am having issues coming up with the proper conditional statement to randomly select a radio-button where the question randomizes 3-5 visible answers per each of the 5 questions per page.

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()

There should be a way of doing this without the frowned upon use of if statements in Cypress. I am a beginning developer so any tips or advice would be greatly appreciated!


回答1:


just some other thought. Since they are all radiobuttons there is no need to create an array and random select one of that array. What you also can do is create a random number between 0 and 4 and combine it with usage of eq().

You already found out how you can select an array-item randomly, same way you can select a number randomly: Math.floor(Math.random() * 5).

So if I take your last part of the code and add the random selection it looks like this:

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


来源:https://stackoverflow.com/questions/57616245/how-to-get-a-random-item-from-an-array-in-cypress-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!