Cypress save value from one function and use it another function

Viewed 49

I have a function which creates random email address at the Signup page. I want to use the returned random email address in Login Page later. How do I do that? This function to create random email is in Commands.js

Cypress.Commands.add('generate_random_string', (string_length) => { 
    let random_string = '';
    let random_ascii;
    for(let i = 0; i < string_length; i++) {
        random_ascii = Math.floor((Math.random() * 25) + 97);
        random_string += String.fromCharCode(random_ascii) 
    }

    return random_string+ '@hotmail.com'
 
   }) 

In my Signup for new account page, I have used this function as the following, I have the following script in fileA.js

 email() {
     return cy.generate_random_string(5).then(random => {
        cy.get('#emailSignup').type(random)
        return cy.wrap(random)
      .as('randomID')
      })
}// this types the email address we generated from the above fn. 

I want just to just get the randomly generated email to be used for later in other tests. Like example: Assertion for Signin page/ signin as the new user using the email generated. I have the following in fileB.js

 assertemailloginpage() {

       cy.get('[data-testid="navigationStack2Route-main"]').contains('randomID')}

another option would be just get the value which got generated from commands.js custom commands. I am not sure how to get the value

2 Answers

You can use the Cypress.env variable to save a value and then use it globally like this:

cy.generate_random_string(5).then((random) => {
  Cypress.env('randomEmail', random)
  cy.get('#emailSignup').type(Cypress.env('randomEmail'))
})

Add a couple of returns into email(). This gets the value out of the POM method.

email() {
  return cy.generate_random_string(5).then(random => {
    cy.get('#emailSignup').type(random)
    return cy.wrap(random)
  })
}

In the test, use .then() to access the returned value.

signup.email().then(emailusedsignup => {
  signuplanding.assertemailloginpage().contains(emailusedsignup) 
})

Once you have one .then() in the chain (in this case cy.generate_random_string(5).then(random =>) it pays to use .then() further down the chain to make sure there's no asynchronous problems.

Related