3

I want to create test request on postman with unique email property in the request body.

{
    ...
    "email": "{{email_string}}.com",
    ...
}

I've set email_string with static string in enviroment, but is there any way that I can set email_string dynamically before request occured?

Vala Khosravi
  • 2,352
  • 3
  • 22
  • 49

3 Answers3

8

You can use Postman's built in support for the Faker library direct in the request body:

{
    ...
    "email": "{{$randomEmail}}",
    ...
}

or, in a pre-request script:

pm.environment.set('user-email', pm.variables.replaceIn('{{$randomEmail}}'));
tom redfern
  • 30,562
  • 14
  • 91
  • 126
  • 1
    This should be the accepted answer - The dynamic variables were introduced after my answer. You can also just use `pm.environment.set('user-email', pm.variables.replaceIn('{{$randomEmail}}'))` to substitute the string in the pre-request script. – Danny Dainton Jan 25 '20 at 08:57
6

As an alternative to the previous answer, you could use the sendRequest function to get the value from a 3rd party API that is designed to return randomised data.

This can be added to the Pre-Request Script tab:

pm.sendRequest("https://randomuser.me/api/", (err, res) => {
    // Get the random value from the response and store it as a variable
    var email = res.json().results[0].email
    // Save the value as an environment variable to use in the body of the request
    pm.environment.set("email_address", JSON.stringify(email))
})

You could potentially create lots of randomised data using this API but it is a 3rd party API so you won't have any control over this changing. If you only need this in the short term, i'm sure it will be fine.

Something also worth remembering is that Postman comes with Lodash built-in so that gives you the ability to use any of that modules functions, to reduce down some of the native JS code.

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
  • 1
    Although this is still a way that can and will work, a much cleaner and more recent option, is the answer that Tom Redfern gave. – Danny Dainton Jan 25 '20 at 08:59
1

There is tab in postman application named "pre-request script" near to "Test" tab. You can use this tab to set your environment variables.

Here is the trick:

var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 5; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
}
postman.setEnvironmentVariable('email_string', text + '@' + text);

I think this script could help you to set a random value in your environment.

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
  • I think, there was a discussion in question "Generate random string/characters in JavaScript" about the fact that Math random is not quite good for this issue. https://stackoverflow.com/a/27747377/11922633 – n-verbitsky Jan 25 '20 at 09:20