CentOS中Postman自定义脚本实用指南
一 脚本类型与执行时机
二 编写脚本的核心语法与示例
pm.environment.get("key")、pm.environment.set("key", "value")pm.globals.get("key")、pm.collectionVariables.get("key")pm.response.text()、pm.response.json()pm.request.url、pm.request.headerspm.test("Status is 200", () => pm.response.to.have.status(200));pm.test("Response < 200ms", () => pm.expect(pm.response.responseTime).to.be.below(200));pm.test("Body contains ok", () => pm.expect(pm.response.text()).to.include("ok"));pm.test("id equals 123", () => pm.expect(pm.response.json().id).to.eql(123));const token = pm.environment.get("token");
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
const json = pm.response.json();
pm.environment.set("userId", json.id);
pm.test("Status 200", () => pm.response.to.have.status(200));
pm.test("Has name", () => pm.expect(json.name).to.be.a("string"));
tests["Status code is 200"] = responseCode.code === 200;(仍可用但不推荐)。三 在CentOS桌面版与Newman中的使用
console.log 输出进行调试。sudo yum install -y nodejs npm 后执行 sudo npm install -g newmannewman run collection.json -e environment.json// run-tests.js
const newman = require('newman');
newman.run({
collection: 'collection.json',
environment: 'environment.json'
}, function (err, summary) {
if (err) { console.error(err); process.exit(1); }
console.log('Collection run complete, summary:', summary.run.stats);
process.exit(summary.run.failures.length > 0 ? 1 : 0);
});
// 执行:node run-tests.js
四 调试技巧与常见问题
console.log 输出;在桌面版左下角打开控制台即可。JSON.stringify() 存储,读取时用 JSON.parse() 还原。tests["..."] = ... 仍可用,建议优先使用 pm.test() 与 pm.expect() 链式断言。