-1

I often come accross lists in the react front ends that I'm currently writing tests for. I wrote this command:

Cypress.Commands.add("click_list", (list_entry) => {
  Cypress.log({
    name: "Choose element from list: ",
  })

  cy.get("li").each((item) => {
    if (item.text().includes(list_entry)) {
      cy.wrap(item).click()
    }
  })
})

Even though it is obviously not well written it does what it should. Still for many of the test cases it is bad practice to predefine the value that shall be clicked. Is there any more elegant way to do this than doing a loop over the elements, then pick a random element from the list and then loop over the elements again until the selected one shows up?

Additional Information:

  • Usually the value is not visible because the lists are long and scrollable
  • Usually there are many seperate lists with equal content so that I cannot just do something like cy.get(that-item).click(). I need to make sure the item actually comes from the list I just clicked on.
MajinBoo
  • 307
  • 1
  • 2
  • 10

1 Answers1

2
Cypress.Commands.add("click_list_randomly", () => {
  Cypress.log({
    name: "Choose random element from list: ",
  })

  cy.get("li").as('list').its('length').then((size) => {
    cy.get('@list').eq(Math.round(Math.rand() * (size - 1))).click({force: true})
  })
})

However, I'm unsure about your statement:

it is bad practice to predefine the value that shall be clicked

Usually, in my experience, you want to be consistent or you potentially introduce flakiness. If you are looking to test all items, you should instead have a test that tries each one. But that may be unnecessary depending on your use case.

adsy
  • 8,531
  • 2
  • 20
  • 31