Cypress while loop

1k Views Asked by At

I have an API that returns times in a day and if those times are all taken then it won't return any. I want to move to the next day and try and check for times there but my test gets stuck and will crash.

So if there are no times go to the next day and wait for the response and check again for times. If there are times return we can exit the loop. Anyone see where this is going wrong?

Thanks

cy.get('body').then(($body) => {
  while (true) {
    if ($body.find('.time').length) {
      break
    } else {
      cy.get('.day').eq(4).click()
      cy.wait('@apiCheck2')
      cy.wait(500)
    }
  }
})
1

There are 1 best solutions below

0
On

You have a selector you want to conditionally test, and a set of actions to perform if not found.

A generic custom command should be able do this. Using jQuery to test for the element(s) based on a selector and a function to call in between attempts.

Something like:

Cypress.Command.add('findWithRetry', (selector, retryAction) {
  const $el = Cypress.$(selector)
  if ($el.length) {
    return cy.wrap($el)
  }
  retryAction()
  return cy.findWithRetry(selector, action)
})

cy.intercept(url).as('@apiCheck')

const retryAction = () => {
  cy.get('.day').eq(4).click()
  cy.wait('@apiCheck')
}

cy.findWithRetry('.time', retryAction)
  .then($timeslots => {
    // use your timeslots
  })