0

I have a requirement that i need to store user email into one variable and then need to use same email to search a user created with same email in another method in cypress how can i do that?

below is my method

class UserManager {
    CreatePrimaryuser() {
        const button = cy.get(':nth-child(2) > a > h3')
        button.click()
        const button1 = cy.get('.btn-edit-user-view')
        button1.click()
        const uemail = cy.get('#emailField')
        var currentDate = new Date();
       var currentTime = currentDate.getTime();
       var commentText = 'Automation' + currentTime + '@email.com';
        uemail.type(commentText)
}
SearchUser() {
        cy.get('#searchUsers').click().type(commentText)

    }

i want to use same value of commontext in searchuser method that is stored in CreatePrimaryuser method

Sumit Soni
  • 29
  • 2
  • 6

2 Answers2

3

You can also save it in an env variable.

class UserManager {
  CreatePrimaryuser() {
    const button = cy.get(':nth-child(2) > a > h3')
    button.click()
    const button1 = cy.get('.btn-edit-user-view')
    button1.click()
    const uemail = cy.get('#emailField')
    var currentDate = new Date();
    var currentTime = currentDate.getTime();
    var commentText = 'Automation' + currentTime + '@email.com';
    uemail.type(commentText)
    Cypress.env('commentText', commentText);
  }

  SearchUser() {
    cy.get('#searchUsers').click().type(Cypress.env('commentText'));
  }
}
  • I see at least 2 drawbacks of the env approach here: 1. An env variable cannot be validated/refactored by IDE or compiler. 2. It's less verbose and hides the relation between the 2 methods. Those flaws may be not so important for a small and stable piece of code but they will smell as soon as your codebase starts to grow – Mikhail Bolotov Sep 24 '21 at 11:00
1

You can just store the value in a field:

class UserManager {
  commentText
  
  constructor() {
    var currentDate = new Date();
    var currentTime = currentDate.getTime();
    this.commentText = 'Automation' + currentTime + '@email.com';
  }

  CreatePrimaryuser() {
    const button = cy.get(':nth-child(2) > a > h3')
    button.click()
    const button1 = cy.get('.btn-edit-user-view')
    button1.click()
    const uemail = cy.get('#emailField')
    
    uemail.type(this.commentText)
  }

  SearchUser() {
    cy.get('#searchUsers').click().type(this.commentText)

  }
}
Mikhail Bolotov
  • 976
  • 1
  • 6
  • 13