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?

1 Like

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:

1 Like

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.