Gia13
Gia13

Reputation: 11

How to select random option from dropdown in cypress

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.

This is HTML: enter image description here

Upvotes: 1

Views: 1305

Answers (3)

Fody
Fody

Reputation: 32044

One approach is to get all your options then click one randomly, using the Attribute Starts With Selector

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)
    const randomOption = $options.eq(randomIndex) 
    cy.wrap(randomOption).click()
  })

Upvotes: 2

TesterDick
TesterDick

Reputation: 10550

The Lodash example given by tlolkema has some mistakes.

The options parameter is an object, not an array. It has a numbered property for each option, but it also has these properties

  • length
  • prevObject
  • selector

The Lodash sample() method can work on an object, but it returns one of the object's properties.

So sometimes Cypress._.sample(options) will return one of the three properties listed above, and your test will fail for unexpected reason.

The correct way to do it is by converting the options to an array first.

You would also cy.wrap() the selected option, not cy.get() it.

cy.get('id^="option-nationality-"]')
  .then(options => {
    const sample = Cypress._.sample(options.toArray())
    cy.wrap(sample).click()
})

Upvotes: 3

tlolkema
tlolkema

Reputation: 278

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

Upvotes: 0

Related Questions