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);
        }
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值