How do I set a global function in Postman?

Austin Cary picture Austin Cary · Oct 12, 2016 · Viewed 7k times · Source

I'd like to declare a function once in the pre-request script of my first postman request and then use it in every request thereafter. I've set plenty of variables on the postman object and as environment variables but I haven't found a way to do the same with functions.

In the pre-request script:

function wrapTest(param1, param2, param3) {
...
}

Then I've tried

  1. postman.prototype.wrap = wrapTest;
    
  2. postman.wrap = wrapTest;
    
  3. postman.setGlobalVariable("wrap", wrapTest);
    

In the request I'm attempting to use this function:

postman.wrap(one,two,three);

which results in "postman.wrap is not a function" in all cases.

Answer

Austin Cary picture Austin Cary · Oct 13, 2016

The function can be saved as a string and then evaled when it's used.

var stringWrap = function wrapTest(param1, param2, param3) {
...
};

postman.setEnvironmentVariable("wrap", stringWrap);
var parsedFunc = eval("("+environment.wrap+")");
parsedFunc("1", 2, 3);