I need help writing a common function to use across a collection of requests which will help with building a framework.
I have tried using the below format
I use this little hack:
pm.globals.set('loadUtils', function loadUtils() {
let utils = {};
utils.reuseableFunction = function reuseableFunction() {
let jsonData = JSON.parse(responseBody);
}
return utils;
} + '; loadUtils();');
tests['Utils initialized'] = true;
In another request I can reuse the global variable loadUtils
:
const utils = eval(globals.loadUtils);
utils.reuseableFunction();
You can also check the developer roadmap of the Postman team. Collection-level scripts are on the near-term agenda and should be available soon until then you can use the shown method.
A more elegant way consists of using the global context (not variables) in the pre-request scripts.
For example, if you wish a function called myFunction
to be available in any pre-request script, you can go to Edit Collection/Pre-request
and set
globalThis.myFunction = function(){}
Then you can call myFunction
in any pre-request script of any request inside the collection (without any stringification/evaluation of your function)