- Published on
Generating data before sending a request
- Authors
- Name
- David Jimenez
In a previous post we learned how to use environment varibles to share data between requests. In that example, we requested a token, and stored it in an environment variable so that we could be reuse it to authenticate future requests.
In that scenario the data that we were sharing was captured after the request was made. However, there may be scenarios where we want to generate data before sending a request.
Going back to our test collection, assume that we want to test that creating accounts works. We don't necessarily care what values we use. A simple solution would be to leverage Postman utilities to generate random data:
{{$randomFullName}}, {{$randomEmail}}, and {{$isoTimestamp}} are generated by Postman. An easy way to tell is that the variable names all start with a dollar sign.
What if we wanted to save those variables to our environment? The first step is to add the variables to the environment. For this example, we'll add three: random_name, random_email, and today_date,
Then in the request's Pre-request Script tab we add JavaScript to populate these variables before making the request:
Two things to note:
- We can still leverage Postman utilities to generate random data. This generates a random email address
pm.variables.replaceIn('{{$randomEmail}}')`
- We can use the
moment
plugin to generate today's date using a year-month-day format.