How to Write Global Functions in Postman

2019-02-21 10:04发布

问题:

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

回答1:

I use this little hack:

postman.setGlobalVariable("loadUtils", function loadUtils() {
    let utils = {};

    utils.reuseableFunction = function reuseableFunction() {

        let jsonData = JSON.parse(responseBody);
        console.log("foobar");
    }

    return utils;

} + '; loadUtils();');
tests['Utils initialized'] = true;

In another request I can reuse the global variable loadUtils:

let utils = eval(globals.loadUtils);
utils.reuseableFunction();

You can also check the developer roadmap of the Postman team here: https://trello.com/b/4N7PnHAz/postman-roadmap-for-developers

Collection-level scripts are on the near-term agenda and should be available soon, until then you can use the shown method.



回答2:

if you want to call pm.sendRequest in global function ,try this:

  1. define global function in collection pre-request, like this:

    postman.setGlobalVariable("globalFunction", (parameters) => { console.log(parameters); pm.sendRequest('https://google.com/', function(err, resp) { pm.expect(err).to.not.be.ok; }); });

  2. use function like this:

    eval(globals.globalFunction)('hello world!!');

Note that, I declared function using arrow style ()=>{}. otherwise it wouldn't work



回答3:

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
});