Steve H
Steve H

Reputation: 378

How can I retry cy.request in cypress with delay, and retry limit

I'm trying to achieve something similar to Cypress request with retry - although comments on that post suggest the solution no longer works / never did work?!

Anyway, I need to send a request to an elastic server, and if no records are returned, wait a bit, then try again (retrying every few (10) seconds, up to say, 2 mins of retries at most)... ie something like:

cy.request({auth,method,body,url...}).then(reqresult => {
  if (reqresult.body.hits.hits.length){
    // results are in elastic, return them
  }
  else {
    cy.wait(10000)
    // repeat the request, if retry attempts not exceeded, or return the empty response if exceeded
  }
})

But everything I've tried (including similar to the post above) has either produced the "mixing async with sync" error, or has simply looped without resending the request, or at worst, has caused my Cypress (10.3.0) window to hang completely!

Can anyone offer any help please?

Upvotes: 3

Views: 1731

Answers (1)

Fody
Fody

Reputation: 31974

Are you looking for Request Polling?

function req (retries = 0) {

  if (retries > 10) throw new Error('Request failed');   // for limit

  cy.request(...)
    .then((resp) => {
      // if we got what we wanted

      if (resp.status === 200 && resp.body.ok === true)
        // break out of the recursive loop
        return

      // else recurse
      cy.wait(10000)            // for delay
        .then(() => req())      // queue the next call
    })
}

req()   // initial call

Upvotes: 5

Related Questions