Pre-request scripts are similar to test scripts but with no assertions. These scripts are run before the request is sent. For example, you can write a pre-request script that calculates a timestamp and save it to a variable and send an HTTP request that uses that variable.
Let's write a pre-request script that generates a new board name in our previous request each time the request is called.
Go to Trello
Create board request. Click on
Pre-request script next to
Tests.
In the
Snippets panel, click on
Set an environment variable. If you don't find it, copy the code below:
pm.globals.set("variable_key", "variable_value");
Name the variable boardName by replacing variable_key
Replace
variable_value with
parseInt(Math.radom() *1000).
Math.random() is a javascript function that generates a number between 0 and 1. We multiply this number by 1000 in order to get a number between 0 and 1000 and we take the integer part only using
parseInt.
pm.globals.set("boardName", parseInt(Math.random() *1000));
When this script is executed, a global variable named boardName is created with a value equal to the randomly generated number.
Go to
Body tab and change the parameter's value as shown below:
Save and click on Send.
Check the response Body. What is the name of your newly created board?
You can see the newly created environment variable by clicking on the eye icon in the top right corner. The value of this variable should be equal to the value concatenated.
Wow done! but still one last thing that does not seem to be working. Your
Test results indicates that there is a failed test.
Click on Test Results. Can you identify what's wrong here and how to fix it?