目录
1.简介
Postman基于Node.js编写,运行时可让您向请求和集合中添加动态行为。这样,您就可以编写测试套件,构建可以包含动态参数的请求,在请求之间传递数据等等。您可以添加JavaScript代码以在2个事件期间执行:
- 一个请求之前被发送到服务器,作为 预请求脚本 的 re-request script 标签。
- 收到响应后,作为 test script 选项卡下的 测试脚本。
2.脚本运行顺序
2.1单个请求
- 与请求关联的预请求脚本将在发送请求之前执行
- 发送请求后,将执行与请求关联的测试脚本
2.2集合中
对于集合中的每个请求,脚本将按以下顺序执行:
- 与集合关联的预请求脚本将在集合中的每个请求之前运行。
- 与文件夹关联的预请求脚本将在文件夹中的每个请求之前运行。
- 与集合关联的测试脚本将在集合中的每个请求之后运行。
- 与文件夹关联的测试脚本将在文件夹中请求后运行。
3.请求前脚本
Pre-request Script : 在将该值传递给第二个请求之前,需要对其进行处理
4.请求后脚本
验证请求返回的数据,可以使用pm.response
对象。
使用pm.test
函数定义测试,并提供一个名称和函数,该函数返回一个布尔值(true
或false
)来指示测试是通过还是失败。
// 断言响应状态码
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
// 使用适合于响应数据格式的语法来确定请求响应的有效性
pm.test("response must be valid and have a body", function () {
pm.response.to.be.ok;
pm.response.to.be.withBody;
pm.response.to.be.json;
});
// 访问环境
pm.test("environment to be production", function () {
pm.expect(pm.environment.get("env")).to.equal("production");
});
5.脚本示例
5.1解析响应数据
// json格式
const responseJson = pm.response.json();
// xml格式
const responseJson = xml2Json(pm.response.text());
const $ = cheerio.load(pm.response.text());
//output the html for testing
console.log($.html());
5.2 断言类型
// 断言类型
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
pm.expect(jsonData).to.be.an("object");
pm.expect(jsonData.name).to.be.a("string");
pm.expect(jsonData.age).to.be.a("number");
pm.expect(jsonData.hobbies).to.be.an("array");
pm.expect(jsonData.website).to.be.undefined;
pm.expect(jsonData.email).to.be.null;
});
5.3断言响应时间
pm.test("Response time is less than 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
5.4断言响应头
// 响应头字段
pm.test("Content-Type header is present", () => {
pm.response.to.have.header("Content-Type");
});
// 响应头字段对应的值
pm.test("Content-Type header is application/json", () => {
pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});
5.5 断言响应主体
pm.test("Person is Jane", () => {
const responseJson = pm.response.json();
pm.expect(responseJson.name).to.eql("Jane");
pm.expect(responseJson.age).to.eql(23);
});
5.6断言状态码
// 断言状态码是否在数组中
pm.test("Successful POST request", () => {
pm.expect(pm.response.code).to.be.oneOf([201,202]);
});
// 断言状态码值
pm.test("Status code is 201", () => {
pm.response.to.have.status(201);
});
5.7 断言Cookie
// 是否存在
pm.test("Cookie JSESSIONID is present", () => {
pm.expect(pm.cookies.has('JSESSIONID')).to.be.true;
});
// 断言cookie 值
pm.test("Cookie isLoggedIn has value 1", () => {
pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');
});
5.8使用多个断言
pm.test("The response has all properties", () => {
//parse the response json and test three properties
const responseJson = pm.response.json();
pm.expect(responseJson.type).to.eql('vip');
pm.expect(responseJson.name).to.be.a('string');
pm.expect(responseJson.id).to.have.lengthOf(1);
});