-2

Console log inside if block prints but return value is empty, why ? i have create let emailHtml varaible to whom i am assigning value in the block

cy.request('GET', `https://api.testmail.app/api/json?apikey=${APIKEY}&namespace=${NAMESPACE}&tag=dev`).then(
      (response) => {
        if (response.body.emails.length != 0) {
          response.body.emails.forEach((email: any) => {
            if (email.subject === subject) {
              emailHtml = email.html;
              console.log(emailHtml); // prints
            }
          });
        }
        if (response.body.emails.length === 0) {
          cy.wait(3000);
          TestMailService.getLatestEmail(subject, ++attempts);
        }
      },
    );
    console.log(emailHtml); // empty

    return emailHtml;
  }
Artjom Prozorov
  • 167
  • 2
  • 10
  • This is a "can I call you back?" scenario. You handed `cy.request` a function. Then, you're concerned that it didn't immediately call that function so that you can see the value of `emailHtml` right away. It's because it's asynchronous. You need to completely return from your function and let some event take place (the request) at which point **it** will call **you** back. – Wyck Jun 20 '22 at 12:08

1 Answers1

0

My solution that might help others

export class TestMailService {
  static async getLatestEmailBySubject(subject: string) {
    let emailAsHtml: string = '';

    const NAMESPACE: string = '';
    const APIKEY: string = '';
    let emailSentTimeStamp: string = Math.round(Date.now() - 120000).toString();

    for (let i = 0; i <= 40; i++) {
      const response: Inbox = await new Cypress.Promise((resolve, reject) => {
        cy.request<Inbox>(
          'GET',
          `https://api.testmail.app/api/json?apikey=${APIKEY}&namespace=${NAMESPACE}&tag=testnow2&timestamp_from=${emailSentTimeStamp}`,
        ).then((response: Inbox) => {
          resolve(response);
          reject('bad request');
        });
      });

      if (response.body.emails.length === 0) {
        cy.wait(3000);
      } else if (
        response.body.emails.length > 0 &&
        response.body.emails[0].subject === subject &&
        response.body.emails[0].timestamp > emailSentTimeStamp
      ) {
        emailAsHtml = response.body.emails[0].html;
        break;
      }
    }
    return emailAsHtml;
  }
}
Artjom Prozorov
  • 167
  • 2
  • 10