How to Write Global Functions in Postman

前端 未结 8 1747
借酒劲吻你
借酒劲吻你 2020-11-30 04:59

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

8条回答
  •  死守一世寂寞
    2020-11-30 05:19

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

提交回复
热议问题