I am trying to choose a random option from a dropdown list. No answers i found so far helped. I have no issues selecting a specific option, since all values have IDs set.
This is simple/straightforward and its working:
const log = new loginPage()
log.visit()
log.loginEmail('test')
log.loginPassword('test')
log.submit()
cy.get('#link-new-application').click()
cy.get('#control-nationality').click()
cy.get('#option-nationality-DZA').click()
Any advice for random selection? I am a beginner so any help would be much appreciated.
Cypress comes with Lodash baked in.
Lodesh brings a lot handy utility methods, with the sample method you can get a random item from a collection.
https://docs.cypress.io/api/utilities/_#Syntax
https://lodash.com/docs#sample
cy.get('id^="option-nationality-"]')
.then(options => {
cy.get(Cypress._.sample(options)).click()
})
One approach is to get all your options then click one randomly
cy.get('#control-nationality').click() // open the dropdown
cy.get('id^="option-nationality-"]') // all elements with id starting "option-nationality"
.then($options => {
const count = $options.length
const randomIndex = Math.floor(Math.random() * count)
$options.eq(randomIndex).click()
})