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 ?
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.
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)