Skip to content
Advertisement

How to reuse a function from an existing Cypress test, and call it in a new one?

I have the following function, which is inside a parent function.

JavaScript

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:

JavaScript

But this didn’t work when I called it inside my test file:

JavaScript

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!

Advertisement

Answer

Just create a custom command on your cypress/support/commands.js like this:

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement