Cy requests retries

Viewed 36

I am attempting creating an email service where cy request will fetch and return body of an email, but logically there could be a case where email did not arrived right away so i assume the correct way is to fetch every 3 seconds and if there is no email try to fetch again so basically retrying same operation over and over for lets say 2 minutes every 3 seconds. Is there something that cypress already have in the api ?

it('Should be able to reset password', () => {
         let emailContent: string = '';
         cy.request(
          'GET',
          `https://api.testmail.app/api/json?apikey=${TestMailService.APIKEY}&namespace=${TestMailService.NAMESPACE}&tag=test&livequery=true`,
        ).then((response) => {
            emailContent =  response.body.emails[0].text;
        });
      })

H

1 Answers

From the docs Request Polling

// a regular ol' function folks
function req () {
  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
      req()
    })
}

It's a recursive function , so I'd add a guard in case of infinite calling (no email shows up).

Waiting 3 seconds is just a cy.wait(3000)

// a regular ol' function folks
function req (attempts = 0) {

  if (attempts === 100) throw 'Too many attempts'

  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(3000)
      req(++attempts)
    })
}

Passing a specific email subject

// TestMailService class

static getLatestEmail(subject: string, attempts = 0): string {

  const NAMESPACE: string = '...';
  const APIKEY: string = '...';

  if (attempts === 40) throw 'No email reached within 2 minutes ';

  return cy.request('GET',         // return the async request
    `api.testmail.app/api/…${APIKEY}&namespace=${NAMESPACE}&tag=dev`)
    .then((response) => {

      if (response.body.emails.length != 0) {
        response.body.emails.forEach((email: any) => {
          if (email.subject === subject) {
            return email.text;       // this modifies what request returns
          }
        });
      }
      if (response.body.emails.length === 0) {
        cy.wait(3000);
        // another return here passes inner results outwards
        return TestMailService.getLatestEmail(subject, ++attempts);   
      }
    })
}

...

TestMailService.getLatestEmail('Registration').then(emailBody => {
  ...
})
Related