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

No, there is a simpler way.

You can define a global object containing functions in the collection pre-request script .
And then you can call the functions in your tests, prefixing by the name of the global object.

For example :

sharedFunctions = {
isArray: function (obj) {
    return Array.isArray(obj)
}

}```

and then call as :  sharedFunctions.isArray(obj)
2 Likes

There is an even easier way.

You just change the function declaration to be a variable assignment so it becomes global scope.

Instead of:

function failure() {
    console.log("failure")
}

do this:

success = function() {
    console.log("success");
}

It’ll even work with parameters:

param = function(input) {
    console.log(input);
}

You call the functions exactly the same way:

success();
param("test");
1 Like