Search code examples
javascripte2e-testingcypress

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


I am new to Cypress and have a small problem which I would like some help on.

I have an input field in my application which allows me to enter a name. This name has to be unique and must not be the same as an existing name already in the system.

I am currently clicking this input field by:
cy.get('input[type="text"].form-control')

If I use the cy.type() command, this will always type in the same value provided, but each time the test runs, I want to assign a different value.

// Fill in some details of a new class to proceed with creation  
cy.get('.pull-left > h4').contains('Add a new class')  
cy.get('input[type="text"].form-control') // Clicks on the field

// Some code to go here to create a random string and use what was created and 
type this into the field above

Expected
Create a function that allows a random string to be generated and then, for that to be typed into the input field by a normal cypress command.


Solution

  • 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;
      }