Global functions via Collection level folder?

I am very sorry if this has already been covered. I have found conflicting information online and just want to know if this is an actual available feature or not.

I want to know if it’s possible to have global functions at the Collection level folder (either in the pre-request or tests section) where I can store any functions I use for nearly every test.

For example say for every request I do the following:

console.log(‘hello!’);

could I instead create a function in say the pre-request section at the Collection level:

function hello() {
console.log(‘hello!’)
}

and they for all my requests I could just call hello(); (I know this isn’t a very practical example) but you know what I mean.

I have also tried this via postman.setGlobalVariable but it did not seem to work either.

Simply defining a function inside the collection pre-request / tests will not make it available everywhere (but it would be nice :slight_smile: ) .

The only way I know to reuse code / define it once run it multiple times is to pack the respective function is a Postman variable and when needed to use eval to run it.

Is this what you are looking for?

2 Likes

Hi @vdespa - thanks for your reply. Your suggestion is what I believe my colleague and I ended up doing. I had come back to this thread to provide an update :slightly_smiling_face:

In the Collection Pre-request script section I add my function(s):

postman.setGlobalVariable("regexFunction", () => {

let regex = /<td>[0-9]{8}<.td>/g;
let regexMatch = bodyResponse.match(regex);
return match[0];
});

Then in my request under Tests:

pageRegex = eval(pm.globals.get("regexFunction"));
pageRegex();

Not the greatest code, but it’s there just to provide context :slight_smile:

2 Likes

That’s what I do @russellg
I used to have evals() that called a function to send a Slack message if there’s a test failure.

That is on the todo list for sure. Not trying to derail my own thread, but if you have any resources that helped you achieve that I’d like to see them.

The problem had perplexed me for a while until I found the common way mentioned above. However, it still leaves a warning icon for each eval line, which indicates “eval can be harmful” in the postman interface.
Recently, I’ve found another way and post it here:
Users can create a prototype object with the proper function you want in the pre-request script section, like this:

Object.prototype.sayHello = function(name){
console.log(Hello! ${name});
};

and call that function everywhere after that. It just required a defined object, like this:

let obj = {};
obj.sayHello(‘Griffin’);

Or you don’t even need the declaration of the object but use some built-in objects instead, like lodash (you pretend it has the function :smile: )

_.sayHello(‘Griffin’);

It’s working on my side.

5 Likes

Fantastic hack! Thanks