Postman-SNIPPETS-内置函数使用

时间:2025-05-09 22:47:10

//(1)方法1:获取token-设置为环境变量

var counterLogin=();

pm.environment.set("token",);

 

//(2)方法2:获取token-设置为全局变量

var counterLogin2=(responseBody);

("token",);

 

//(3)获取接口中的某响应头-获取Content-Type

var ContentType=postman.getResponseHeader("Content-Type");

("Content-Type", ContentType);

 

//


 

//(3)判断接口响应值是否是200

//Status code:Code is 200

("Status code is 200", function () {

    (200);

});

 

//(4)检查接口响应值中是否包含登录成功字样,【若include中包含则返回"Body matches 登录成功"】

//Response body:Contains string

("Body matches 登录成功", function () {

    (()).("登录成功");

});

 

//(5)检查JSON中的某个值是否等于预期【(jsonData.字段名称).(字段返回值)】

//Response body:JSON value check

("code=200,success=true,message=登录成功", function () {

    var jsonData = ();

    ().(200);

    ().(true);

    ().("登录成功");

});

 

//(6)检查响应体是否等于response_body_string字符【("接口响应值精确匹配");】

//Response body:Is equal to a string

("Body is correct", function () {

    ("接口返回详情精确匹配值,JSON则需要转义");

});

 

//(7)接口响应头Content-Type检查是否存在

//Response headers:Content-Type header check

("Content-Type is present", function () {

    ("Content-Type");

});

 

//(8)接口响应时间是否小于200毫秒,如果是返回pass

//Pesponse time is less than 200ms

("Response time is less than 20ms", function () {

    ().(200);

});

 

//(9)接口响应code包含[201, 202,200],若包含201,202,200则返回true

//Status code:Successful POST request

("Successful POST request", function () {

    ().([201, 202,200]);

});


 

//(10)Status Code的返回值是否包含对应的字符【包含OK字符,若包含则返回pass】

//Status code:Code name has string

("Status code name has string", function () {

    ("OK");

});

 

//(11)将XML格式的响应体转换为JSON格式

//Response body:Convert XML body to a JSON Object

var jsonObject = xml2Json(responseBody);