Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write Global Functions in Postman

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

like image 624
Anji R Avatar asked Aug 14 '17 11:08

Anji R


People also ask

How do you make a global function?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you write a Postman function?

To write your first test script, open a request in Postman, then select the Tests tab. Enter the following JavaScript code: pm. test("Status code is 200", function () { pm.

What is global and local variable in Postman?

Postman, which is used for various activities, supports the following variable scopes. Local is the smallest variable scope, followed by Data, Environment, Collection, and Global. Global Variables functions outside of the environment and are not affected by it.


2 Answers

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());
like image 87
ggutenberg Avatar answered Oct 17 '22 02:10

ggutenberg


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.

like image 34
Sergej Lopatkin Avatar answered Oct 17 '22 02:10

Sergej Lopatkin