How do I store a parameter in a variable and then use that parameter in a test?

I searched online for 20 minutes already.

I have a param called billerCode.

How do I store that in a variable in the prescript so that I can use it in the test?
For example I tried this but itā€™s not working:
var billerCode = pm.request.url.query.get(ā€œbillerCodeā€);

console.log(billerCode);

Itā€™s saying itā€™s undefined.

UPDATE: Itā€™s a path variable not a query param, so the solution was pm.request.url.variables.get(ā€˜billerCodeā€™);

Thread can be deleted unless you want to keep it around. Thanks.

Hi @TesterShaner,

Hereā€™s an example of how you can extract all of the query parameters from your request (in case you have multiple parameters), and then how you can specifically get to the billerCode:

var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
var billerCode = query["billerCode"]; 

Thank you Neil for the response!
I figured out my problem just as you sent that, my variable is a path variable not a query param.
So I needed to do: pm.request.url.variables.get(ā€˜billerCodeā€™);

I will take your code into my cheat sheet as well. Thanks!

How come this code works in the Pre-request script area but it doesnā€™t work in the tests area?

var billerCode = pm.request.url.variables.get(ā€œbillerCodeā€);
console.log("Biller code is: " + billerCode);

I want to create a variable in the pre-request script area and then reference it in the tests area, or just create the variable in the tests area.

Basically Iā€™m getting the billerCode from the path variable and then I want to verify that value is in the body response. What am I doing wrong?

Youā€™re not doing anything wrong! You canā€™t directly call pm.request.url.variables from the Tests tab, because by the time this code is executed, the path variables have all been resolved (itā€™s just a single, fully-formed string by this point).

The best way to track the value between the Pre-Request and Tests tab would be to push it through in a temporary local variable, i.e:

Pre-request tab:
pm.variables.set("billerCode", pm.request.url.variables.get("billerCode"));

Tests tab:
console.log("Biller code is: " + pm.variables.get("billerCode"));

2 Likes