Shared function between tests

How to share function between calls

I defined function in Pre-request script on collection level
function mySharedFunc(){ console.log("mySharedFunc is called"); } mySharedFunc()

if I go to Tests tab dedicated to single call of this collection and start typing function name mySha… then postman highlights that it knows this function, so far so good, but when I make a call
I see this in console:

“mySharedFunc is called” //comes from collection pre-request
“ReferenceError: mySharedFunc is not defined” //comes from call itself

Question: why it tells me that function is not defined ?
is the only way to share function on collection level is to put function into collection variable and then eval it ?

Hi @dave101ua

The collection level pre-request script is not a place to store functions.
It gets executed before each and every call made within the collection.

If you added just your console log line;

console.log("mySharedFunc is called");

to the collection level pre-request script, it would run for every API call within the collection.

If you want to be able to call your function whenever you choose, then you would have to (as far as I’m aware) store it in a variable and eval it as you mentioned.

1 Like