Defining function at Collection level pre-request scripts

As from the documentation, both pre-request scripts and test are run in the order:

  • Collection
  • Folder
  • Request

This way Iโ€™m trying to define a function at the Collection level and call it at Folder and Request level.
Is it possible?

Example:

// Collection pre-request script
function foo(){
  console.log('bar')
}
// Request pre-request script
foo()

By now it interupt the resquest to be sent with the error message:

There was an error in evaluating the Pre-request Script:
ReferenceError: foo is not defined

Thereโ€™s any other way to achieve that: Be able to define a function in collection level and access it at the sub-levels?
Thanks!!

Hey @artu-hnrq :wave:

Welcome to the Postman community :postman:

Is this something that could help here?

https://www.postman.com/postman/workspace/postman-answers/collection/1794236-d4aabd0d-f2c4-4905-80a5-61b35ebc54d4?action=share&source=copy-link&creator=8213448

1 Like

Yeah, it worked, @danny-dainton :tada:
Thanks for the agile answer

So the ideia is to get the target function (or an utils object) from the global scope through pm.globals.get and evaluate it on the current scope!

The mentioned example can be updated accordingly:

// Request pre-request script
eval(pm.globals.get('foo'))
foo()
1 Like

Nice one, glad it helped. :trophy:

I believe the request in that Collection already had those eval statements, in the pre-request and tests script environments.