如何在 Postman 中编写全局函数

2022-01-22 00:00:00 postman javascript

我需要帮助编写一个通用函数以在一组请求中使用,这将有助于构建框架.

I need help writing a common function to use across a collection of requests which will help with building a framework.

我尝试过使用以下格式

以下函数在第一个函数的Test选项卡中声明

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

我收到以下错误

评估预请求脚本时出错:无法读取未定义的属性function1".

谁能帮我定义全局/通用函数并在请求中使用它们?

Can anyone help me with how to define Global/common functions and use them across the requests?

提前致谢

推荐答案

没有eval:

在集合的预请求脚本中定义一个包含您的函数的对象,而不使用 letvar 等.这会将其附加到 Postman 的全局沙箱对象.

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

相关文章