Creating a random string in Cypress and passing this to a cy command

Try this code.Hope This will work.

cy.get(':nth-child(2) > :nth-child(2) > input').type(userID_Alpha())
function userID_Alpha() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    for (var i = 0; i < 10; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

OR Use the following code

cy.get(':nth-child(2) > :nth-child(2) > input').type(userID_Alpha_Numeric())      

function userID_Alpha_Numeric() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 10; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

I just found another approach in a blog, adding it here for reference.

const uuid = () => Cypress._.random(0, 1e6)
const id = uuid()
const testname = `testname${id}`
cy.get('input').type(testname);

worked well for me :)


Given you need less than 1 id per millisecond, you don't need unique values in parallel environments, and you are not a time traveller, you may use Date.now().

If you need more than 1 id per millisecond, you may use Date.now() as a seed for Cypress._.uniqueId():

const uniqueSeed = Date.now().toString();
const getUniqueId = () => Cypress._.uniqueId(uniqueSeed);

it('uses a unique id', () => {
  const uniqueId = getUniqueId();
});