How to Write Global Functions in Postman
JavascriptPostmanJavascript Problem Overview
I need help writing a common function to use across a collection of requests which will help with building a framework.
I have tried using the below format
The following function is declared in the Test tab in the first function
postman.setGlobalVariable("function", function function1(parameters)
{
//sample code
});
I used the following in the pre-request
var delay = eval(globals.function);
delay.function1(value1);
I am getting the following error
there was error while evaluating the Pre-request script : Cannot read property 'function1' of undefined.
Can anyone help me with how to define Global/common functions and use them across the requests?
Thanks in advance
Javascript Solutions
Solution 1 - Javascript
Without eval
:
Define an object containing your function(s) in the collection's pre-request scripts without using let
, var
, etc. This attaches it to Postman's global sandbox object.
utils = {
myFunc: function() {
return 'hello';
}
};
Then within your request's pre-request or test script section just call the function:
console.log(utils.myFunc());
Solution 2 - Javascript
I use this little hack:
pm.globals.set('loadUtils', function loadUtils() {
let utils = {};
utils.reuseableFunction = function reuseableFunction() {
let jsonData = JSON.parse(responseBody);
}
return utils;
} + '; loadUtils();');
tests['Utils initialized'] = true;
In another request I can reuse the global variable loadUtils
:
const utils = eval(globals.loadUtils);
utils.reuseableFunction();
You can also check the developer roadmap of the Postman team. Collection-level scripts are on the near-term agenda and should be available soon until then you can use the shown method.
Solution 3 - Javascript
Edit: The following answer is still valid and you can skip ahead and read it, but I want to give a warning first: If you are trying use this in Postman, you should probably use something else than Postman, like Mocha, for your testing. Postman is OK for small to medium scale applications but very large multi-developers applications can be a nightmare to maintain with postman. The in-app editor is a mess for large files, and versioning can be problematic.
ANSWER
You can have a more readable solution and more possibility to factor your code (like calling function1()
from function2()
directly inside your pre-request script, or declaring packages) with the following syntax :
Initialize environment (or globals) :
postman.setEnvironmentVariable("utils", () => {
var myFunction1 = () => {
//do something
}
var myFunction2 = () => {
let func1Result = myFunction1();
//do something else
}
return {
myPackage: {
myFunction1,
myFunction2
}
};
});
And then use your functions in a later test :
let utils = eval(environment.utils)();
utils.myPackage.myFunction1(); //calls myFunction1()
utils.myPackage.myFunction2(); //calls myFunction2() which uses myFunction1()
Bonus :
If you are calling an API and need to wait the call to finish before performing a test, you can do something like this:
postman.setEnvironmentVariable("utils", () => {
var myFunction = (callback) => {
return pm.sendRequest({
// call your API with postman here
}, function (err, res) {
if (callback) {
//if a callback method has been given, it's called
callback();
}
});
}
return {
myPackage: {
myFunction,
}
};
});
and then to use it:
utils.myPackage.myFunction(function() {
console.log("this is the callback !")
//perform test here
});
Solution 4 - Javascript
If you want to call pm.sendRequest
in a global function, try this:
-
Define the global function in collection pre-request, like this:
pm.globals.set('globalFunction', parameters => { console.log(parameters); pm.sendRequest('https://google.com/', function(err, resp) { pm.expect(err).to.not.be.ok; }); });
-
Use function like this:
eval(globals.globalFunction)('hello world!!');
Note that, I declared function using arrow style ()=>{}
. Otherwise, it wouldn't work.
Solution 5 - Javascript
The problem had perplexed me for a while until I found the common way mentioned above. However, it still leaves a warning icon for each eval line, which indicates “eval can be harmful” in the postman interface. Recently, I’ve found another way and post it here: Users can create a prototype object with the proper function you want in the pre-request script section, like this:
Object.prototype.sayHello = function(name){
console.log(`Hello! ${name}`);
};
and call that function everywhere after that. It just required a defined object, like this:
let obj = {};
obj.sayHello(‘Griffin’);
Or you don’t even need the declaration of the object but use some built-in objects instead, like lodash (you pretend it has the function :smile: )
_.sayHello(‘Griffin’);
It’s working on my side. I also posted it in postman forum here https://community.postman.com/t/global-functions-via-collection-level-folder/5927/6?u=franksunnn110
Solution 6 - Javascript
Very easy to achieve with monkey patch on object (or whatever you want).
Option #1
On collection level pre script
Object.prototype.doSomething = (foo) => console.log(foo);
On any other place:
pm.doSomething('bar');
// or
postman.doSomething('bar');
Option #2
On collection level pre script
Utilities = {};
Utilities.getParam = (foo) => console.log(foo);
On any other place
Utilities.getParam('bar');
Solution 7 - Javascript
A more elegant way consists of using the global context (not variables) in the pre-request scripts.
For example, if you wish a function called myFunction
to be available in any pre-request script, you can go to Edit Collection/Pre-request
and set
globalThis.myFunction = function(){}
Then you can call myFunction
in any pre-request script of any request inside the collection (without any stringification/evaluation of your function)
Solution 8 - Javascript
You can declare a global function by assigning this function into a collection, environment or global variable as follows:
- Create a collection variable, i.e. global_func
- In the variable value write this code,
> (number)=> { return number * number }
to reuse this function elsewhere in your collection
let numberSquared = eval(pm.variables.get('global_func'))(5)
now, numberSqaure variables has a value of 25
================================
if you need to declare a function library: you can create a collection variable and assign it this piece of code:
({
print:function() {
console.log('hello Postman')
},
squared:function(number) {
return number * number
}
})
Note: the functions have been enclosed with parentheses
to reuse this library:
let lib = eval(pm.variables.get('global_func'))
lib1.print()
console.log(lib1.squared(4))
Good luck :)
Solution 9 - Javascript
If you want to be able to use pm.response
in your global function, pass this
as parameter.
In your collection pre-request :
Utils = {
myFunc: function(that) {
return that.pm.response;
}
};
And use it in your request pre-request or test script like this :
Utils.myFunc(this);
Solution 10 - Javascript
Define functions as a global variables then access across all of your tests.
pm.environment.set("UTILS", `({ myFunction: (text) => console.log(text) })`)
Call the functions
let utils = eval(pm.environment.get("UTILS"))
utils.myFunction('Test')
Solution 11 - Javascript
A lot of the above examples will have issues with pm variable. In order to have access to pm variable inside your custom utils method you need to pass it inside after eval. On top of that it is nice to have some modularity for your utils. Paste this as a value for a global variable under name -> Util
(function () {
const Util = function (pm) {
return {
customUtilFunction: function (customVariable) {
pm.environment.set("customVariable", customVariable);
}
}
}
return Util
}())
And then inside your test you can call it like presented below.
const Util = eval(pm.globals.get('Util'))(pm)
Util.customUtilFunction('myCustomVariableValue')