Random in cypress

Viewed 87

I need to tell this function to return a random number of each variable that is within those lengths

    it('dates', ()=>{     
      cy.description('Leonel','Andress Messi')      
      cy.get('#mat-input-4').type(dob())    
      
      function dob() {       
        var day = Math.random(10, 31)      
        var month = Math.random(10, 12)     
        var year = Math.random(1940, 2000)      
        return month + '/' + day + '/' + year    
      }
     })
2 Answers

See Getting a random number between two values

Note the upper limit of random() is excluded.

Also, be careful of 30 days in November, calculate the month first.

function getRandomArbitrary(min, max) {
  const upper = max + 1                      // random() upper limit is excluded
  return Math.floor(Math.random() * (max - min) + min)
}

function dob() {
  const month = getRandomArbitrary(10, 12)

  const day = month === 11 ? getRandomArbitrary(10, 30) : getRandomArbitrary(10, 31)

  const year = getRandomArbitrary(1940, 2000)    

  return month + '/' + day + '/' + year
}

cy.log(dob())  
cy.log(dob())
cy.log(dob())
cy.log(dob())

enter image description here

how are you?

In this case, you can just create your dob function in another js file, example created a file called utils.js in your support directory, in your utils.js file put write your function like this:

export default class Utils {

    dob = () => {
        
        var day = Math.random(10, 31)
        
        var month = Math.random(10, 12)
        
        var year = Math.random(1940, 2000)
        
        return month + '/' + day + '/' + year
        
  }
}

In your spec Cypress test file import your Utils and call the dob method in your it:

import Utils from '../../support/Utils';

it('dates', ()=>{
  utils = new Utils();

  cy.description('Leonel','Andress Messi')
        
  cy.get('#mat-input-4').type(dob())
        
  const date = utils.dob()
})
Related