Linux 下 Postman 创建脚本的完整指南
一 环境准备
二 在 Postman 中创建脚本
三 常用脚本示例
// Pre-request Script
const ts = new Date().toISOString();
pm.environment.set("timestamp", ts);
// Pre-request Script
pm.request.headers.add({
key: "X-Request-Id",
value: "req-" + Math.random().toString(36).substr(2, 9)
});
// Tests
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
pm.test("Response contains success", () => {
const json = pm.response.json();
pm.expect(json).to.have.property("message", "success");
});
// Tests
const json = pm.response.json();
pm.environment.set("authToken", json.token);
// Pre-request Script
const dep = {
url: "https://postman-echo.com/get?k=fromDep",
method: "GET"
};
pm.sendRequest(dep, (err, res) => {
if (!err) {
const v = res.json().args.k;
pm.collectionVariables.set("fromDep", v);
}
});
以上示例展示了变量、请求修改、发送请求与断言的常用模式,可直接粘贴到对应脚本面板测试。
四 在 Linux 终端运行脚本与集成 CI
# 基本运行
newman run collection.json
# 指定环境
newman run collection.json -e environment.json
# 生成报告(HTML 示例)
newman run collection.json -e environment.json -r html