Skip to content
Advertisement

Why can’t I add a simple reusable function to Postman?

In Postman, I’m trying to achieve the following:

  1. In a collection:
    1. Create a utility object containing reusable functions
    2. Store that utility object in a global variable for later use in request test scripts.
  2. In a request:
    1. Pull the utility object code out of the global variables.
    2. Eval the code and store the resulting utility object instance in a local variable.
    3. Invoke a method on the utility object instance.

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:

  • Converting the entire function to a multi-line string and storing that result in the globals environment. The same error occurred.
  • Including the enclosing parentheses directly in the function body. That didn’t work, either.
  • Using lambda expressions, but that caused all sorts of problems in the editor itself.

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

Advertisement

Answer

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 + ")()");
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement