I have the following function, which is inside a parent function.
// A function that creates a random string and will later pass this to a variable
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
}
var random_string = generate_random_string(6)
I have many uses for this random string generator, inside of other test files for different scenarios. Instead of having to copy and paste this each time, I want to reuse this function and call it inside another test file.
How should I set this up?
I tried to create a custom command inside the commands.js
file like so:
Cypress.Commands.add("random_string_gen",
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
})
But this didn't work when I called it inside my test file:
cy.get('#name').click()
cy.get('#name').random_string_gen()
I want to reuse the function inside one file, and call it inside another, but I am not sure how to set up the necessary command/index JS files, so a template to get me started would be really helpful!
To run button_all. js inside another test, wrap it's code in a function. You can also pass params to modify each run. export function runButtonAllTests(testParams) { describe('Global Button Patterns', () => { context('mobile', () => { if (testParams.
The proper way to do this would be to follow the Custom Command syntax. Put this in your support/commands. js file: Cypress.
Just create a custom command on your cypress/support/commands.js
like this:
Cypress.Commands.add('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
});
Then, on your test spec files you can call cy.generate_random_string(5)
.
For example, this will print to the console a random generated string with a length of 5.
/// <reference types="Cypress" />
context('stackoverflow', () => {
it('stackoverflow', () => {
cy.generate_random_string(5).then((result) => {
console.log(result);
});
})
})
// Output: eauyy
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