random generated string function in command.js is not getting recognized in e2e loginTest.js - Cypress

Viewed 51

I copied this code below and have it in my support/command.js. I am using the following function to create multiple username for login functionality using Cypress JS.

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+ '@gmail.com'



   });

Then, In my loginTest.Spec, I am calling it like below

const {commands} = require('../support/commands')

const { Input } = require("@angular/core")
const { wrap } = require("module")
const { isExportSpecifier } = require("typescript")



describe('our first suite', () => {

    it('first test', () => {
        cy.visit('/')
        cy.get('a[data-tracking-name="Sign up for free"]').click()
        cy.get('.flex').should('contain',"Create your free account")
        cy.get('[for="emailSignup"]').should('contain',"Work email")

        // cy.get('#emailSignup').type(generate_random_string(5))
        cy.generate_random_string(5).then(random => {
            cy.get('#emailSignup').type(random)
          })
        // cy.get('#emailSignup').type("John18002@gmail.com")
        cy.contains('button', 'Continue').click()
        cy.get('#fullName').type('IamTest User')
        cy.get('#password').type('AHJQ*234')
        cy.get('[type="submit"]').click()
        cy.window().then((win) =>  {
            cy.stub(win,'alert').as('alert')


        })

        cy.get('.flex').contains('Close').click()



    })
})

I am getting generate_random_string is not defined message. I tried creating a new file under support with the above function and tried importing in commands.js and then use it in the loginSpec file but even that didn't work. Using web based automation tool almost after 6 yrs and I am not sure what I am doing wrong. Much appreciate your help.

1 Answers

The TLDR is custom commands don't return values the same way functions do.

If you want to use it like this

cy.get('#emailSignup').type(generate_random_string())

then it should be a plain function, not a custom command.

const 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 + '@gmail.com'
}

If you want to keep it as a custom command, use it like this

cy.generate_random_string(10).then(random => {
  cy.get('#emailSignup').type(random)
})
Related