Postman:常用脚本

判断数组是否为空

function isEmpty(value) {
  return (Array.isArray(value) && value.length === 0) || (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);

时间等待

function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	    }
}

sleep(4000);

Json转String

var aToStr=JSON.stringify(a);

设置全局变量

pm.globals.set("access_token", pm.response.json().access_token);

正则表达式

var s = pm.response.text().match(/(.*)?csrf_token" value="(.*)?"\/>/gi,1);
var t = s[0].replace(/.*value="|"\/>/g,"");
console.log(t);

用代码发送请求

  1. 先使用 Postman 创建一个请求
  2. 把该请求 Export 到本地
  3. 打开 json 文件,找到 item 下的想要发送的请求的 request 信息,如:
"request": {
				"method": "POST",
				"header": [
					{
						"key": "Referer",
						"value": "https://{{host}}/login"
					},
					{
						"key": "Content-Type",
						"value": "application/json"
					}
				],
				"body": {
					"mode": "raw",
					"raw": "{\"UserName\":\"{{username}}\",\"PassWd\":\"{{password}}\",\"pattern\":null}"
				},
				"url": "https://{{host}}/api/V1/login"
			}
  1. 把 request 的值赋值给变量 req
req = {
				"method": "POST",
				"header": [
					{
						"key": "Referer",
						"value": "https://{{host}}/login"
					},
					{
						"key": "Content-Type",
						"value": "application/json"
					}
				],
				"body": {
					"mode": "raw",
					"raw": "{\"UserName\":\"{{username}}\",\"PassWd\":\"{{password}}\",\"pattern\":null}"
				},
				"url": "https://{{host}}/api/V1/login"
			}

  1. 通过 Postman 的帮助生成发送请求的代码并修改请求地址为 req
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

修改为:

pm.sendRequest(req, function (err, response) {
	//response为该接口的返回值
    console.log(response.json());
});

异常捕获


pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    try{
          var id = jsonData.data[0].parcelId;
           pm.environment.set("parcelId", id);
        }catch(err){
          console.log("parcelId is null");
          console.log(err)
          console.log(err.message);
        }
});
posted @ 2021-04-21 17:37  Feng1024  阅读(267)  评论(0编辑  收藏  举报