How we can use faker in Postman v 7.2

Now postman support faker library in v 7.2

How we can use it any code example ?

I want to create some fake data in pre request script.

Hey @mehran.shafqat

You will find more information about it here, these are dynamic variables and would work in the same places that {{$randomInt}} can be used.

1 Like

well why this is not working in pre-req script

var x = “{{$randomInt}}”
console.log (x)

its not printing any random value

Taken from the dynamic variables section:

Note that dynamic variables cannot be used in the Sandbox. You can only use them in the {{…}} format in the request URL / headers / body.

{{$guid}}: Adds a v4 style guid
{{$timestamp}}: Adds the current timestamp
{{$randomInt}}: Adds a random integer between 0 and 1000

That’s expected behavior because in pre-request script the variables are not resolved.

There’s a workaround:

const {Property} = require('postman-collection');

let randomInt = Property.replaceSubstitutions("{{$randomInt}}");

console.log(randomInt)

We are planning to add an API for variable substitution in scripts.
Please follow the original GitHub feature request for more updates.

2 Likes

I’ve seen many of these new random variables available now in the API and I have used in the app but they are not “resolved” when the test is run via Newman.

Hey @alkamist-dgrandfield,

What version of Newman are you running this against?

Hi all,

a bit late to the party, but since I found a working solution, I wanted to share with you.

The faker.js file needs to be on a webserver accessible by postman.
So what I did is to create a public Bitbucket repo (guess github would work as well), and put all files and subdirectories from https://github.com/Marak/faker.js/tree/master/build/build into it.
I then viewed the faker.js file in RAW mode in Bitbucket and copied the URL, this is what I will be using as faker_js_url in the Postman pre-request-sccript.

And this is a snippet to be used in the pre-request-Script, of course you can easily save the generated values in an environment variable for later re-use:

pm.sendRequest(faker_js_url, (err, res) => {
const faker = res.text();
(new Function(faker))();
    var name = window.faker.name.findName();
    console.log (name);
});

(Inspired by Adding external libraries to postman)

What I´m currently struggling with, is setting the faker locale.
Any help with that is much appreciated.

Hello there Christian,

This is what worked for me to get the faker locale working in the test script:

window = {};
pm.sendRequest(“https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js”, (error, response) => {
var text = response.text();
(new Function(text))();

window.faker.locale = “de”;
var name = window.faker.name.findName();

console.log(name);

pm.globals.set(“name”, name);
})

1 Like