How can I run a Cypress Command within a synchronous loop?

Viewed 360

I am working on a flashcard app where each flashcard has a "term" and a "definition".

Each form field is accessible by a "data-testid" of either "term-{index value}" or "definition={index value}"

The code I've been trying to execute looks something like this:

let i = 0
let randomNumber = Math.floor(Math.random() * 20))
while (i < randomNumber) {
  // Run Cypress code using "i" variable value
}

Currently, Cypress won't run the code.

I believe my issue has to do with the asynchronous nature of Cypress and the synchronous nature of the code above. Would anyone happen to know how I can get something like this code working?

1 Answers

You can use each()to iterate through an array-like structure (arrays or objects with a length property). Something like:

cy.get('data-testid').each(($el, index, $list) => {
    //$el is the unique element
    //index starts with 0 and with each iteration its value increases by 1
    //$list contains the number of unique elements
})
Related