How to Write Global Functions in Postman

前端 未结 8 1713
借酒劲吻你
借酒劲吻你 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:26

    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.

    0 讨论(0)
  • 2020-11-30 05:31

    A more elegant way consists of using the global context (not variables) in the pre-request scripts. For example, if you wish a function called myFunction to be available in any pre-request script, you can go to Edit Collection/Pre-request and set

    globalThis.myFunction = function(){}
    

    Then you can call myFunction in any pre-request script of any request inside the collection (without any stringification/evaluation of your function)

    0 讨论(0)
提交回复
热议问题