postman常用的JavaScript

Pre-request Script

get an environment variable

pm.environment.get(“variable_key”);

get an global variable

pm.globals.get(“variable_key”);

get an variable

pm.variables.get(“variable_key”);

set an environment variable(设置环境变量)

pm.environment.set(“variable_key”, “variable_value”);

set an global variable(设置全局变量)

pm.globals.set(“variable_key”, “variable_value”);

clear an environment variable

pm.environment.unset(“variable_key”);

clear an global variable

pm.globals.unset(“variable_key”);

send a request(通过url发送一个请求,并将返回结果打印出来)

pm.sendRequest(“https://postman-echo.com/get”, function (err, response) {
console.log(response.json());
});

Tests

status code:code is 200(通过相应状态判断响应是否正常)

pm.test(“Status code is 200”, function () {
pm.response.to.have.status(200);
});

Response Body:contains string(响应体是否包含某个期望的字符串,实际就是关键词)

pm.test(“Body matches string”, function () {
pm.expect(pm.response.text()).to.include(“string_you_want_to_search”);
});

Response Body:json value check(响应体json里面是否包含期望的值)

pm.test(“Your test name”, function () {
var jsonData = pm.response.json();
pm.expect(jsonData.value).to.eql(100);
});

Response Body:is equal to a string(判断返回内容是否跟预期完全相等。)

pm.test(“Body is correct”, function () {
pm.response.to.have.body(“response_body_string”);
});

Response headers:Content-type header check(响应头是否包含content-type header)

pm.test(“Content-Type is present”, function () {
pm.response.to.have.header(“Content-Type”);
});

Response time is less than 200ms(响应时间不超过多长)

pm.test(“Response time is less than 200ms”, function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});

Status code:successful post request(判断post是否请求成功,请求成功的response code包含201、202)

pm.test(“Successful POST request”, function () {
pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

Status code:no name has string

pm.test(“Status code name has string”, function () {
pm.response.to.have.status(“Created”);
});

response body:convert xml body to a json object(将xml内容转换成json)

var jsonObject = xml2Json(responseBody);

use tiny validator for json data(验证json数据是否正确)

var schema = {
“items”: {
“type”: “boolean”
}
};
var data1 = [true, false];
var data2 = [true, 123];
pm.test(‘Schema is valid’, function() {
pm.expect(tv4.validate(data1, schema)).to.be.true;
pm.expect(tv4.validate(data2, schema)).to.be.true;
});

将响应体的数据转化为json格式

var jsonData = pm.response.json();
pm.environment.set(“token”,jsonData.result.json[‘token’]);
或者pm.environment.set(“token”,jsonData.json[‘token’]);

发布了46 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24601279/article/details/103473352