邮递员:如何创建预请求脚本以使用数组中的随机元素设置环境变量

问题描述 投票:-2回答:1

我需要在邮递员中创建一个预请求脚本,以在值数组中使用随机元素设置环境变量。有谁有想法?

编辑:(已解决)

<!-- language: lang-js -->
var order_id = ["one","two","three","four","five"];



function getRandomInt(min, max) { 

min = Math.ceil(min); 
max = Math.floor(max); 

return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive 
} 
pm.environment.set("order_id", order_id[getRandomInt(0,4)]);
arrays random postman
1个回答
0
投票

Postman有许多内置模块,允许您执行此类操作,而无需以这种方式编写本机JS代码。

删除该函数,只需添加它,它将使用Lodash random()函数执行相同的操作:

var order_id = ["one","two","three","four","five"]

pm.environment.set("order_id", order_id[_.random(0,4)]

)

或者只使用Lodash shuffle功能:

var order_id = ["one","two","three","four","five"]

pm.environment.set("order_id", _.shuffle(order_id)[0])
© www.soinside.com 2019 - 2024. All rights reserved.