I want to enter dynamic text in cypress, so at each run, the name field will not have repeated input, for example name1, name 2...
So in the js file I would have something like
And("I enter a name", () => {
portalPage.roleName().type("Cypress admin" + 1, { force: true })
})
Any help is appreciated.
Between runs you have to write the last used number to a fixture,
And("I enter a name", () => {
cy.fixture('name-num.json').then(num =>
const next = num +1;
portalPage.roleName().type(`Cypress admin ${next}`, { force: true })
cy.writeFile('cypress/fixtures/name-num.json', next.toString())
})
If you do this multiple times in the same run, cy.fixture won't work because it caches the value it reads.
Instead use readFile()
And("I enter a name", () => {
cy.readFile('cypress/fixtures/name-num.json').then(num =>
const next = num +1;
portalPage.roleName().type(`Cypress admin ${next}`, { force: true })
cy.writeFile('cypress/fixtures/name-num.json', next.toString())
})
If you are seeking random inputs, then lodash .random() will generate a random number from 0 to the input.
// will generate random number between 0 and 9999
portalPage.roleName().type(`Cypress admin${Cypress._.random(9999)}`, { force: true })
If you only needed the values to be different within the same spec, you could store the value in a Cypress environment variable. The environment variable will not be cleared until the spec has finished running.
And("I enter a name", () => {
// set the environment variable to current value + 1, or if it hasn't been set, 1.
Cypress.env("myNumber", Cypress.env("myNumber")++ ?? 1);
// use the environment variable
portalPage.roleName().type("Cypress admin" + Cypress.env("myNumber"), { force: true });
})