My question:
What is the correct way of creating a global class instance so I could access and reuse it as a utility class for my Collection test requests?
I am exploring this approach instead of creating multiple global functions and storing them individually in global/collection variables which the latter was suggested in other posts (Global functions via Collection level folder)
Here is a sample public collection that I created to illustrate my approach:
Test Scratchpad
Details:
In my Collection Pre-request script I declared a class TestUtil with a formatDate() function. I created an instance of this class and stored it in a Collection variable “utilityclass”.
class TestUtil {
constructor () {};
/**
* Utility function to convert a date to ISO string yyyy-mm-dd format.
*/
formatDate(date) {
let yourDate = new Date(date);
yourDate.toISOString().split('T')[0];
const offset = yourDate.getTimezoneOffset();
yourDate = new Date(yourDate.getTime() - (offset*60000));
return yourDate.toISOString().split('T')[0];
};
};
util1 = new TestUtil();
console.log("Collection Pre-req: " + util1.formatDate(pm.variables.replaceIn('{{$randomDatePast}}')));
pm.collectionVariables.set("utilityclass", util1);
// check if TestUtil instance was really set in collection variables for later use.
util2 = pm.collectionVariables.get("utilityclass");
console.log("Collection Pre-req: " + util2.formatDate(pm.variables.replaceIn('{{$randomDatePast}}')));
In my test request, I retrieve the instance of this class using:
let util3 = pm.collectionVariables.get("utilityclass");
// Why can't Postman resolve util3.formatDate() as valid function?
console.log("Test Global Class Pre-req - util3.formatDate(): " + util3.formatDate(pm.variables.replaceIn('{{$randomDatePast}}')));
Postman is throwing an Error exception stating “util3.formatDate is not a function”.
However if I try to access directly the class instance I created in the Collection pre-request script, Postman allows this and resolves the class instance correctlyl. I am trying to understand why is this so, and what is the correct way to achieve what I am trying to do.
// util2 is declared in the Collection pre-request script.
// Why does Postman allow me to access this object directly and resolves formatDate() correctly?
console.log("Test Global Class Pre-req - util2.formatDate(): " + util2.formatDate(pm.variables.replaceIn('{{$randomDatePast}}')));