In Postman, I'm trying to achieve the following:
None of the many implementations I've seen scattered across the web seem to work, though. I can get all the way down to step 2.2, and then things just die a horrible flaming death. The JavaScript engine beneath Postman refuses to evaluate the object stored in the globals collection.
To isolate the issue, I've stripped this down to a bare minimum script, which is placed in the pre-request scripts for my collection:
postman.setGlobalVariable("loadUtils", function utils() {
let utils = {};
utils.main = function() {
console.log("Hello, world!");
}
return utils;
} + ';utils()');
I then try to load this script as follows:
var code = globals.loadUtils;
console.log(code);
var utils = eval('(' + code + ')');
But the following error always occurs:
There was an error in evaluating the test script: SyntaxError: Unexpected token ;
I tried:
I'm certain that this is something simple, stupid, and obvious, and that I am just not seeing it.
Can someone please point out what I am doing wrong here?
P.S. This should be possible, as suggested here on StackOverflow and the Postman forums on GitHub (though it requires some scrolling through the comments to see the solution).
You store two statements as a string, which are seperated by a semicolon:
"function utils() { /*...*/ }; utils()"
then you wrap that string in parentheses and try to execute it:
eval("(function { /*...*/ }; utils())")
that won't work, as a ; inside of an expression is a syntax error.
You either remove the parens, replace the semicolon with a colon or use an IIFE (which I'd favor here):
eval("(" + someFunc + ")()");
Instead of using eval, add something like the following to your Collection's pre request script.
/* You can add collection level functions to this utils object that will be available throughout
the collection's requests' pre-request scripts and tests. */
utils = {
/** This is an example function
* @param pm pass the current pm so that this has the correct context
*/
reusableFunction: function(pm) {
console.log("do something amazing here instead of just logging, including manipulating environment or request, access the response, etc. That is why you pass in the pm. Request: " + JSON.stringify(pm.request));
}
}
This function is usable in any of the collection request's pre-request script or tests.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With