skip to Main Content

My problem is I created two methods that will generate a random first name and random last name from the arrays of names. When the test executes the first and the last name methods, I want to somehow get those two values and combine them into an email in the specific format -> "[email protected]".

But I don’t know how to do it and I can’t find the answer that works. Keep in mind I work in Cypress for a few days. Below is the photo of the fields and HTML of the element (both are the same in terms of where the value is stored).

function generateEmail(){
  var email = cy.get("input[placeholder='Enter first name']") + "." +  
    cy.get("input[placeholder='Enter last name']") + "@gmail.com"
  return email
}

enter image description here

I don’t know what to use in order to get the text from the value attribute.

2

Answers


  1. function generateEmail() {
    return Promise.all([
        cy.get("input[placeholder='Enter first name']").invoke('val'),
        cy.get("input[placeholder='Enter last name']").invoke('val')
      ]).then(([firstName, lastName]) => {
        const email = `${firstName}.${lastName}@gmail.com`;
        return email;
      });
    }
    

    Call generateEmail funtion

     generateEmail().then((email) => {
          console.log(email);
        });
    

    Call Another Way

    async function getEmail() {
      const email = await generateEmail();
      console.log(email);
    }
    
    getEmail();
    
    Login or Signup to reply.
  2. Generally speaking you will use .then() to get a value from cy.get() but since they are inputs you also need .invoke('val') to extract the value entered into the <input>.

    Return the whole chain and use it with .then(), or create a custom command instead of a function.

    function generateEmail() { 
      return cy.get("input[placeholder='Enter first name']").invoke('val')
        .then(first => {
          cy.get("input[placeholder='Enter last name']").invoke('val')
            .then(last => {
              return first  + "." + last + "@gmail.com"
            })
        })
    }
    
    ...
    
    generateEmail()
      .then(email => {
        expect(email).to.eq('[email protected])  // it works!
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search