pm 对象 API
全局方法
pm
pm:Object
pm对象包含了接口(或测试集)运行的相关信息,并且可以通过它访问需要发送的请求信息和发送后返回的结果信息。另外还可以通过它get或set环境变量和全局变量。
pm.info:Object
pm.info 对象包含了接口(或测试集)运行的相关信息。
pm.info.eventName:String当前执行是什么类型的脚本:前置脚本(prerequest),或后置脚本(test)。
pm.info.iteration:Number当前执行第几轮循环(iteration),仅集合测试有效。
pm.info.iterationCount:Number本次执行需要循环的总轮数,仅集合测试有效。
pm.info.requestName:String当前正在运行的接口用例名称
pm.info.requestId:String当前正在运行的接口用例名称的唯一 ID
pm.sendRequest
pm.sendRequest:Function
pm.sendRequest 用途为在脚本内异步发送 HTTP/HTTPS 请求。
- 该方法接受一个 collection SDK 兼容的 request 参数和一个 callback 函数参数。 callback 有 2 个参数,第一个是 error ,第二个是 collection SDK 兼容的 response。更多信息请查阅 Collection SDK 文档 。
- 在前置脚本和后置脚本都可以使用。
// GET 请求示例
pm.sendRequest("https://postman-echo.com/get", function(err, res) {
if (err) {
console.log(err);
} else {
pm.environment.set("variable_key", "new_value");
}
});
// 完整的 request 参数示例
const echoPostRequest = {
url: "https://postman-echo.com/post",
method: "POST",
header: {
headername1: "value1",
headername2: "value2",
},
// body 为 x-www-form-urlencoded 格式
body: {
mode: "urlencoded", // 此处为 urlencoded
// 此处为 urlencoded
urlencoded: [
{ key: "account", value: "apifox" },
{ key: "password", value: "123456" },
],
},
/*
// body 为 form-data 格式
body: {
mode: 'formdata', // 此处为 formdata
// 此处为 formdata
formdata: [
{ key: 'account', value: 'apifox' },
{ key: 'password', value: '123456' }
]
}
// body 为 json 格式
header: {
"Content-Type": "application/json", // 注意:header 需要加上 Content-Type
},
body: {
mode: 'raw',// 此处为 raw
raw: JSON.stringify({ account: 'apifox', password:'123456' }), // 序列化后的 json 字符串
}
// body 为 raw 或 json 格式
body: {
mode: 'raw',
raw: '此处为 body 内容',
}
*/
};
pm.sendRequest(echoPostRequest, function(err, res) {
console.log(err ? err : res.json());
});
// 对返回结果进行断言
pm.sendRequest("https://postman-echo.com/get", function(err, res) {
if (err) {
console.log(err);
}
pm.test("response should be okay to process", function() {
pm.expect(err).to.equal(null);
pm.expect(res).to.have.property("code", 200);
pm.expect(res).to.have.property("status", "OK");
});
});
参考:
pm.variables
pm.variables: Variable SDK 参考
临时变量。不同类型的变量,有不同的优先级,不同类型变量的优先级顺序为: 临时变量 > 环境变量 > 项目全局变量 > 团队全局变量。
pm.variables.has(variableName:String):function → Boolean: 检查是否存在某个临时变量。pm.variables.get(variableName:String):function → *: get 单个临时变量。pm.variables.set(variableName:String, variableValue:String):function → void: set 单个临时变量。pm.variables.replaceIn(variableName:String):function: 以真实的值替换字符串里包含的“动态变量”,如{{variable_name}}。示例:// 定义一个包含动态变量的字符串
let stringWithVariable = "Hello, {{username}}";
// 使用 replaceIn 方法替换掉 {{username}} 变量占位符
let realValueString = pm.variables.replaceIn(stringWithVariable);
// 输出替换后的值
console.log(realValueString); // 输出: "Hello, john_doe"pm.variables.replaceInAsync(variableName:String):function: 以真实的值替换字符串里包含的“动态值表达式”,如{{$person.fullName}}。返回 Promise,调用时需加await。示例:// 定义一个包含动态值表达式的字符串
let stringWithVariable = "Hello, {{$person.fullName}}";
// 使用 replaceInAsync 方法替换掉 {{$person.fullName}} 占位符
let realValueString = await pm.variables.replaceInAsync(stringWithVariable);pm.variables.toObject():function → Object: 以对象形式获取所有临时变量。
pm.iterationData
pm.iterationData:
测试数据变量,因为测试数据是单独管理的,暂不支持在脚本中直接设置测试数据变量,但是您可以在脚本中访问测试数据变量,如下。
pm.iterationData.has(variableName:String):function → Boolean: 检查是否存在某个测试数据变量。pm.iterationData.get(variableName:String):function → *: get 单个测试数据变量。pm.iterationData.replaceIn(variableName:String):function: 以真实的值替换字符串里包含的“动态变量”,如{{variable_name}}。pm.iterationData.toObject():function → Object: 以对象形式获取所有测试数据变量。
pm.environment
pm.environment.name:String: 环境名。pm.environment.has(variableName:String):function → Boolean:检查是否存在某个环境变量。pm.environment.get(variableName:String):function → *:get 单个环境变量。pm.environment.set(variableName:String, variableValue:String):function:set 单个环境变量。pm.environment.replaceIn(variableName:String):function:以真实的值替换字符串里的包含的动态变量,如{{variable_name}}。pm.environment.toObject():function → Object:以对象形式获取当前环境的所有变量。pm.environment.unset(variableName:String):function: unset 单个环境变量。pm.environment.clear():function:清空当前环境的所有变量。
注意:
以上所有操作都是读写的本地值,而不会读写远程值。
pm.globals
pm.globals.has(variableName:String):function → Boolean:检查是否存在某个全局变量。pm.globals.get(variableName:String,variableScope:String):function → *:get 单个全局变量。 可以使用 'PROJECT' (默认)或 'TEAM' 来选择全局变量范围。pm.globals.set(variableName:String,variableValue:String, variableScope:String):function:set 单个全局变量。可以使用 'PROJECT' (默认)或 'TEAM' 来选择全局变量范围。pm.globals.replaceIn(variableName:String):function:以真实的值替换字符串里的包含的动态变量,如{{variable_name}}。如前置脚本,获取请求参数的值如果包含变量,则需要使用
pm.globals.replaceIn才能将变量替换会真正的值。pm.globals.toObject():function → Object:以对象形式获取所有全局变量。pm.globals.unset(variableName:String):function: unset 单个全局变量。pm.globals.unset(variableName:String,variableScope:String):function: unset 单个全局变量。可以使用 'PROJECT' (默认)或 'TEAM' 来选择全局变量范围。pm.globals.clear():function:清空当前环境的全局变量。
- 以上所有操作都是读写的
本地值,而不会读写远程值。 - 当使用 set 并带上 'TEAM' 变量范围时,只会更改已有同名团队变量的
本地值。如果当前不存在此名称的团队变量,则不会新增一个团队变量,而是把本次 set 的变量当做临时变量来使用。
pm.request
pm.request: Request SDK 参考
request 是接口请求对象。在前置脚本中表示将要发送的请求,在后置脚本中表示已经发送了的请求。
request 包含了以下结构:
pm.request.url:Url: 当前请求的 URL。pm.request.getBaseUrl():获取当前运行环境选择的的前置 URL,在 2.1.39 版本之后支持。pm.request.headers:HeaderList:当前请求的 headers 列表。pm.request.method:String当前请求的方法,如GET、POST等。pm.request.body:RequestBody: 当前请求的 body 体。pm.request.headers.add({ key: headerName:String, value: headerValue:String}):function: 给当前请求添加一个 key 为headerName的 header。pm.request.headers.remove(headerName:String):function: 删除当前请求里 key 为headerName的 headerpm.request.headers.get(headerName:String):function: 查询当前请求里的headerName。pm.request.headers.upsert({ key: headerName:String, value: headerValue:String}):function: upsert key 为headerName的 header(如不存在则新增,如已存在则修改)。pm.request.auth: 当前请求的身份验证信息
使用示例:
在后置操作中填入自定义脚本,参考下图示例,选择所需要的提取对象,编写对应的函数。
例如提取请求中的 headers 中的 Accept 值并打印到控制台。

pm.response
以下部分 API 仅在
后置脚本中可用
pm.response: Response SDK 参考
在后置脚本中 pm.response 接口请求完成后返回的 response 信息。
response 包含了以下结构:
pm.response.code:Numberpm.response.status:Stringpm.response.headers:HeaderListpm.response.responseTime:Numberpm.response.responseSize:Numberpm.response.text():Function → Stringpm.response.json():Function → Objectpm.response.setBody('')pm.response.headers.get: Response SDK 参考
在后置脚本中使用 pm.response.headers.get 命令可以提取返回响应中的 headers 中的值。例如想要在控制台中显示 Header 中的 Date 值,那么可以在后置操作中填写如下自定义脚本:
var test = pm.response.headers.get("Date")
console.log(test)

若希望将其作为变量供其它接口调用,详细说明请参考《最佳实践:接口之间如何传递数据?》
pm.cookies
pm.cookies: CookieList SDK 参考
cookies 为当前请求对应域名下的 cookie 列表。
pm.cookies.has(cookieName:String):Function → Boolean检查是否存在名为
cookieName的 cookie 值pm.cookies.get(cookieName:String):Function → Stringget 名为
cookieName的 cookie 值pm.cookies.toObject:Function → Object以对象形式获取当前域名下所有 cookie
pm.cookies.jar().clear(pm.request.getBaseUrl())清空全局 cookies
pm.cookies 为接口请求后返回的 cookie,而不是接口请求发出去的 cookie。
pm.test
pm.test(testName:String, specFunction:Function):Function
该方法用来断言某个结果是否符合预期。
以下示例为检查返回的 respone 是否正确:
pm.test("response should be okay to process", function() {
pm.response.to.not.be.error;
pm.response.to.have.jsonBody("");
pm.response.to.not.have.jsonBody("error");
});
通过 callback 的可选参数 done ,还可用来测试异步方法:
pm.test("async test", function(done) {
setTimeout(() => {
pm.expect(pm.response.code).to.equal(200);
done();
}, 1500);
});
pm.test.index():Function → NumberGet the total number tests from a specific location.
pm.expect
pm.expect(assertion:*):Function → Assertion
pm.expect 是一个普通的断言方法,查看详细的说明:ChaiJS expect BDD library。
该方法用来断言 response 或 variables里的数据非常有用,更多关于 pm.expect断言的是示例,可以点击这里查看:Assertion library examples
Response 对象可用的断言 API 列表
pm.response.to.have.status(code:Number)pm.response.to.have.status(reason:String)pm.response.to.have.header(key:String)pm.response.to.have.header(key:String, optionalValue:String)pm.response.to.have.body()pm.response.to.have.body(optionalValue:String)pm.response.to.have.body(optionalValue:RegExp)pm.response.to.have.jsonBody()pm.response.to.have.jsonBody(optionalExpectEqual:Object)pm.response.to.have.jsonBody(optionalExpectPath:String)pm.response.to.have.jsonBody(optionalExpectPath:String, optionalValue:*)pm.response.to.have.jsonSchema(schema:Object)pm.response.to.have.jsonSchema(schema:Object, ajvOptions:Object)
pm.response.to.be
pm.response.to.be 是用来快速断言的一系列内置规则。
pm.response.to.be.info检查状态码是否为
1XXpm.response.to.be.success检查状态码是否为
2XXpm.response.to.be.redirection检查状态码是否为
3XXpm.response.to.be.clientError检查状态码是否为
4XXpm.response.to.be.serverError检查状态码是否为
5XXpm.response.to.be.error检查状态码是否为
4XX或5XXpm.response.to.be.ok检查状态码是否为
200pm.response.to.be.accepted检查状态码是否为
202pm.response.to.be.badRequest检查状态码是否为
400pm.response.to.be.unauthorized检查状态码是否为
401pm.response.to.be.forbidden检查状态码是否为
403pm.response.to.be.notFound检查状态码是否为
404pm.response.to.be.rateLimited检查状态码是否为
429