When you run a feature file in karate, first things it looks for a karate-config.js file in your classpath and contain a javascript function. The function is expected to return a JSON object and all keys and values in that JSON object will be made available as script variables.

Now let’s say you want to pass a random string to your feature file or a random UUID. You can do this by adding a such function in your karate-config file and then use it by the specifying the config variable key.
In the below image I have added a function that generates a random string and stores in a config variable name “randomName”

function fn() {
karate.configure('connectTimeout', 5000);
karate.configure('readTimeout', 5000);
var config = { // base config JSON
username: 'QAtechtools',
password: '************',
baseURL: 'https://api.github.com',
randomName: makeid()
};
function makeid() {
var length=5;
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
return config;
}
We will see now how to use the variable named randomName in your feature file.

Scenario: creating a repo and verifying the response
* path '/user/repos'
#Change the repo_name and any other fields
* def createRepoBody = read('createRepo.json')
#Get the data from the config function in the JS file
* def name = randomName
#Setting the name for the request
* set createRepoBody.name = name
#Add the final body in the request
And request (createRepoBody)
* method post
#verify the status code
* status 201
* print response