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.

// 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!

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement