13

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.

Jas
  • 805
  • 3
  • 12
  • 21
  • 1
    Is there some sort of API that checks to see if the name is unique? What is the mechanism that checks your string to see if it was used before? I would intercept the API request that checks the duplicate name so you can control it. You could use the date string, or a guid.. – Maccurt Jan 09 '19 at 16:36

7 Answers7

26

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 :)

briancaffey
  • 2,339
  • 6
  • 34
  • 62
CuriousSoul230
  • 315
  • 5
  • 9
5

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;
  }
KunduK
  • 32,888
  • 5
  • 17
  • 41
  • 2
    New Cypress-user here... Can this be written into a Cypress Custom command? Or where is a good place to store a helper-function as this one, assuming that it's used in several tests? – Zeth Jul 12 '19 at 16:00
5

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();
});
meesvandongen
  • 317
  • 3
  • 8
1

There is a better way of doing that. Check this link for the complete package details. https://www.npmjs.com/package/faker

First add the Faker library by running the following npm command.

npm install faker

Next call the relevant faker data generation commands wherever data is inputed to the system by your Cypress automated test.

const faker = require("faker");
cy.get('input').type(faker.random.alphaNumeric());
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Ashis Raj
  • 53
  • 4
  • FYI, that package has been discontinued--an understatement--by the maintaner. https://arstechnica.com/information-technology/2022/01/foss-developer-who-nuked-his-apps-embraced-qanon-theory-involving-aaron-swartz/ – Mike C Feb 17 '22 at 14:43
  • Use this one instead. https://www.npmjs.com/package/@faker-js/faker – Ashis Raj Mar 03 '22 at 19:06
0

I am making some assumptions here. I assume there is some sort of API that you call to check if there is a duplicate name. I would stub/mock that to get around it. I am taking a guess here, but you pass down the name and you get something back that says true or false, you stub that to always return false, so you can do your duplicate.

Maccurt
  • 12,655
  • 7
  • 32
  • 43
0

I created a single function that generates the random string, then create a variable to store this value and then use the value within the logic of the rest of the test.

    function 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
    }

I then assign this to a variable below:

var random_string = generate_random_string(8)

Then the extracted output from that and put into the field by using the simple get and type commands in Cypress:

cy.get('input[type="text"].form-control').type(random_string)

This gets the value and types it into the field that I wanted. I can also "random_string" again in any test, say for example if I wish to do some assertions later on in the test.

Jas
  • 805
  • 3
  • 12
  • 21
0
example.spec.js

it('timestamp', function() {
cy.task('datenow').then((random) => { cy.log('test' + random)})
}) 

plugins/index.js

on('task', {
datenow () {
return Date.now()
}
}) 

The above code will generate random strings