In this article I will show you how easy it is to generate random data in your k6 load test scripts.
As a brief context, in the real projects, there are moments when an API endpoint requires unique values on its request body because there might be some unique value constraints in the database, and so on.
Let’s think about a user registration process, where we cannot have multiple users registered with the same email or username.
For this use case, we will implement some random data in our test. I will be using k6 Test API application, that contains a POST endpoint for user registration. As you can see, the request body implies unique values for username and email properties.

Happily, k6 provides utility functions that we can use out of the box to generate random numbers between a given interval, random strings, items, and so on – docs HERE
Code Example
For demo purpose, we are going to use randomString function that accepts length value as argument
1. import randomString function into your script
import { randomString } from ‘https://jslib.k6.io/k6-utils/1.2.0/index.js’;
2. define a constant and initialize it with randomString(length)
const randomEmail = randomString(15) + “@gmail.com”;
const randomUsername = randomString(10);

Source code
You can find the source code HERE
Enjoyed this article? Make sure to subscribe to my YouTube Channel for more Test Automation tutorials, and follow me on LinkedIn and Twitter for regular insights.
Looking to accelerate your test automation journey?
I’ve designed a personalized 1-on-1 mentoring program tailored to boost your skills. Reach out at iamqarv@gmail.com for more details 🚀