Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

question from:https://stackoverflow.com/questions/45673961/how-to-write-global-functions-in-postman

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
117 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...