Leo
Leo

Reputation: 3

How to skip cy.get() function inside a for loop

Cypress commands are asynchronous which means each Cypress command returns immediately, having only been appended to a queue of commands to be executed at a later time.

I have a function which reload the page until some condition is met.

Below code is working but the problem is that cy.get() is always executed for [retry] times, which is not good.

Could you please show me some insight how it can be optimized?

export function waitMoniliphToComplete(retry) {
  let numRows = 0
  let stopLoop = false
  cy.wait(1000)
  cy.reload()
  for (let i = 0; i < retry; i++) {
    if (stopLoop) {
      break
    }
    cy.get('#consignment-list tbody tr').then($rows => {
      if ($rows.length == 0 || $rows.length != numRows) {
        numRows = $rows.length
        cy.wait(1000)
        cy.reload()
      } else if ($rows.length == numRows) {
        stopLoop = true
      }
    })
  }
}

Currently cy.get() is queued by cypress and will be executed [retry] times no matter in which iteration stopLoop is true.

I expect cy.get() can be skipped once the condition stopLoop is met.

Upvotes: 0

Views: 834

Answers (1)

bbsimonbb
bbsimonbb

Reputation: 28992

I suspect you need to chain the reload and the get, to make sure the reload has happened before you count the rows. Try using recursion...

function reloadAndTest(){
    cy.reload().get('...').then(rows => {
        if(rows || ++retries === limitRetries)
            return true
        else return reloadAndTest()
    })
};

Upvotes: 1

Related Questions