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.
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();
});
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With