Generate random values in Postman to use in your tests

When you want your tests to be able to run whenever you want, you should use values which are random.

In Postman, click on the name of Collection and then open the ‘Pre-request Script’ tab.

There, add the following:

// get a random number between a minimum and a maximum
// gives you current datetime with milliseconds like 2022810_171012_174
postman.setGlobalVariable("getCurrentDate",  () => {
  const date=new Date(); 
  return String(date.getFullYear())  
      + String(date.getMonth()+1) 
      + String(date.getDate()) 
      + '_' 
      + String(date.getHours() < 10 ? "0"+date.getHours() : date.getHours()) 
      + String(date.getMinutes() < 10 ? "0"+date.getMinutes() : date.getMinutes()) 
      + String(date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds())
      + '_' 
      + String(date.getMilliseconds())
})

You can now use this function in your tests. This enables you to make your strings (like emailaddresses) random by adding the current datetime to it.

To use it, open your test, click on the ‘Pre-request Script’ tab and add the following.

var currentDate = eval(pm.globals.get("getCurrentDate"))();
var randomEmail = `postman-${currentDate}@pauledenburg.com`;
pm.environment.set("randomEmail", randomEmail);

You can now use the generated value in the body of your POST-request by referencing it as {{randomEmail}}

Click Here to Leave a Comment Below

Leave a Reply: