Search code examples
javascriptpromiseautomated-testscypresstimeout

Promise with timeout calling a function


I have a function below and I would like to set a timeout. If the execution of this function exceeds 2 minutes, timeout and the next test flow follows.

Does anyone know how I add a setTimeOut inside my function?

Function:

function resWait() {
    cy.req(
      'GET',
      `${url}/transaction/acquirertrxquery?acquirerId=1&dateFrom=${actualDate}%2000:00:00&dateTo=${actualDate}%2023:59:00&externalId=${idExternal}`
    ).then((res) => {
      if (res.body.content[0].trxConfirmationStatus.description === 'Confirmed') {
        return
      }
      cy.wait(3000)
      resWait()
    })
  }

I would like to use Promise. But I don't know how to fit the promise into my function! I have this example. How do I make this promise call my function or work the timeout?

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Would you help me?

Thanks in advance!!


Solution

  • I would rather suggest you control the retry executions by a maximum number of attempts, something like the following code. It's easier and safer to control in this way than setting a promise timeout because the recursive exit is more explicit and less prone to errors. And you can set the number of attempts and the cy.wait time in a way that matches your desired 2 minutes

    function resWait(attemptsRemaining = 10) {
      cy.req(
        'GET',
        `${url}/transaction/acquirertrxquery?acquirerId=1&dateFrom=${actualDate}%2000:00:00&dateTo=${actualDate}%2023:59:00&externalId=${idExternal}`
      ).then((res) => {
        const isStatusConfirmed = res.body.content[0].trxConfirmationStatus.description === 'Confirmed';
        const noMoreAttemptsLeft = attemptsRemaining === 0;
    
        if (isStatusConfirmed || noMoreAttemptsLeft) {
          return
        }
    
        cy.wait(3000)
    
        resWait(attemptsRemaining - 1)
      })
    }