'Cypress - Loop looking for data and refresh if not found

I need to loop looking for an item in a table and if it's not found, click a refresh button to reload the table. I know I can't use a simple while loop due to the asynchronous nature of cypress. Is there another way to accomplish something like this.

I tried to tweak an example from another post but no luck. Here's my failed attempt.

    let arry = []
    for (let i = 0; i < 60; i++) { arry.push(i) }
    cy.wrap(arry).each(() => {
        cy.get('table[class*="MyTableClass"]').then(function($lookForTheItemInTheTable) {
            if($lookForTheItemInTheTable.find("MySearchValue")) {
                return true
            }
            else {
                cy.get('a[class*="selRefreshTable"]').click()
                cy.wait(2000)
            }
        })
    })


Solution 1:[1]

Cypress is bundled with lodash. Instead of using a for loop, you can the _.times(). However, I wouldn't recommend this for your situation as you do not know how many times you would like to reiterate.

You'll want to use the cypress-recurse plugin and use it like this example in that repo:

import { recurse } from 'cypress-recurse'

it('gets 7 after 50 iterations or 30 seconds', () => {
  recurse(
    () => cy.task('randomNumber'), // actions you want to iterate
    (n) => n === 7, // until this condition is satisfied
    { // options to pass along
      log: true,
      limit: 50, // max number of iterations
      timeout: 30000, // time limit in ms
      delay: 300 // delay before next iteration, ms
    },
  )
})

Even with the above mentioned, there may be a simplified approach to solving your problem with setting up your app to have the table always display what you are seeking on the first try.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jjhelguero