Generate random user data in Postman pre-request script
Preconditions (3)
✅ Expected Result: The request is sent with unique random user data each time, visible in the request body or headers, and environment variables hold the generated values.
Jump into concepts and practice - no test required
pm.environment.set('firstName', `User${Math.floor(Math.random() * 1000)}`); pm.environment.set('lastName', `Test${Math.floor(Math.random() * 1000)}`); const email = `user${Math.floor(Math.random() * 1000)}@example.com`; pm.environment.set('email', email); console.log(`Generated user: ${pm.environment.get('firstName')} ${pm.environment.get('lastName')} <${pm.environment.get('email')}>`);
This script runs before the request is sent. It generates random numbers between 0 and 999 and appends them to fixed strings to create unique first names, last names, and emails.
We use pm.environment.set to save these values as environment variables. This way, the request can use {{firstName}}, {{lastName}}, and {{email}} placeholders in the body or headers.
The console.log helps to see the generated data in Postman's console for debugging.
Now add data-driven testing by generating random user data for three different user roles: admin, editor, and viewer.
const names = ['Alice', 'Bob', 'Charlie'];
const randomIndex = Math.floor(Math.random() * names.length);
pm.environment.set('randomName', names[randomIndex]);var randomNum = Math.random() * 1000;
pm.environment.set('email', 'user' + randomNum + '@test.com');