Postman 提供了可在請求腳本中使用的 JavaScript API。該pm對象提供了用于測試您的請求和響應數(shù)據的功能,該postman對象提供了額外的工作流控制。
您將使用 執(zhí)行大部分 Postman JavaScript API 功能pm.*,它提供對請求和響應數(shù)據以及變量的訪問。
您可以使用 API 在 Postman 的每個范圍內訪問和操作變量pm。
您可以在請求運行時使用動態(tài)變量生成值。
Postman 支持多種變量作用域。該pm對象提供了專門訪問全局變量、集合變量和環(huán)境變量的方法,以及pm.variables訪問不同范圍變量和設置局部變量的方法。
pm.variables.has(variableName:String):function → Boolean
pm.variables.get(variableName:String):function → *
pm.variables.set(variableName:String, variableValue:*):function
pm.variables.replaceIn(variableName:String):function: → *
例如:
const stringWithVars = pm.variables.replaceIn("Hi, my name is {{$randomFirstName}}");
console.log(stringWithVars);
pm.variables.toObject():function → Object
變量作用域決定了當你引用變量時 Postman 賦予它們的優(yōu)先級,按照優(yōu)先級遞增的順序:
具有最接近范圍的變量會覆蓋任何其他變量。例如,如果您score在當前集合和活動環(huán)境中都有命名的變量,并且您調用pm.variables.get('score'),Postman 將返回環(huán)境變量的當前值。當您使用 設置變量值時pm.variables.set,該值是本地的,并且只會在當前請求或收集運行時持續(xù)存在。
//collection var 'score' = 1
//environment var 'score' = 2
//first request run
console.log(pm.variables.get('score'));//outputs 2
console.log(pm.collectionVariables.get('score'));//outputs 1
console.log(pm.environment.get('score'));//outputs 2
//second request run
pm.variables.set('score', 3);//local var
console.log(pm.variables.get('score'));//outputs 3
//third request run
console.log(pm.variables.get('score'));//outputs 2
有關詳細信息,請參閱Postman Collection SDK 變量參考。
您還可以使用pm.environment、pm.collectionVariables和pm.globals訪問在各個范圍中定義的變量。
您的腳本可以使用這些pm.environment方法來訪問和操作活動(當前選擇的)環(huán)境中的變量。
pm.environment.name:String
pm.environment.has(variableName:String):function → Boolean
pm.environment.get(variableName:String):function → *
pm.environment.set(variableName:String, variableValue:*):function
pm.environment.replaceIn(variableName:String):function → *
例如:
//environment has vars firstName and age
const stringWithVars = pm.environment.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.environment.toObject():function → Object
pm.environment.unset(variableName:String):function
pm.environment.clear():function
請注意,您編輯變量的能力取決于您在工作區(qū)中的訪問級別。
您的腳本可以使用這些pm.collectionVariables方法來訪問和操作集合中的變量。
pm.collectionVariables.has(variableName:String):function → Boolean
pm.collectionVariables.get(variableName:String):function → *
pm.collectionVariables.set(variableName:String, variableValue:*):function
pm.collectionVariables.replaceIn(variableName:String):function → *
例如:
//collection has vars firstName and age
const stringWithVars = pm.collectionVariables.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.collectionVariables.toObject():function → Object
pm.collectionVariables.unset(variableName:String):function
pm.collectionVariables.clear():function
您的腳本可以使用這些pm.globals方法在工作區(qū)內的全局范圍內訪問和操作變量。
pm.globals.has(variableName:String):function → Boolean
pm.globals.get(variableName:String):function → *
pm.globals.set(variableName:String, variableValue:*):function
pm.globals.replaceIn(variableName:String):function → String
例如:
//globals include vars firstName and age
const stringWithVars = pm.globals.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.globals.toObject():function → Object
pm.globals.unset(variableName:String):function
pm.globals.clear():function
請注意,您編輯變量的能力取決于您在工作區(qū)中的訪問級別。
您的腳本可以使用這些方法在收集運行期間pm.iterationData訪問和操作數(shù)據文件中的變量。
pm.iterationData.has(variableName:String):function → boolean
pm.iterationData.get(variableName:String):function → *
pm.iterationData.toObject():function → Object
pm.iterationData.toJSON():function → *
pm.iterationData.unset(key:String):function
有多種方法可以訪問 Postman 腳本中的請求和響應數(shù)據,包括pm.request、pm.response、pm.info和pm.cookies。此外,您可以使用pm.sendRequest發(fā)送請求。
該pm.request對象為運行腳本的請求提供對數(shù)據的訪問。對于預請求腳本,這是即將運行的請求,對于測試腳本,這是已經運行的請求。
您可以使用pm.request對象預請求腳本在運行之前更改請求配置的各個部分。
該pm.request對象提供以下屬性和方法:
pm.request.url:Url
pm.request.headers:HeaderList
pm.request.method:String
pm.request.body:RequestBody
pm.request.headers.add(header:Header):function
例如:
pm.request.headers.add({
key: "client-id",
value: "abcdef"
});
pm.request.headers.remove(headerName:String):function
pm.request.headers.upsert({key: headerName:String, value: headerValue:String}):function)
有關詳細信息,請參閱 Postman Collection SDK 請求參考。
該對象提供對添加到Tests 的pm.response腳本中當前請求的響應中返回的數(shù)據的訪問。
該pm.response對象提供以下屬性和方法:
pm.response.code:Number
pm.response.status:String
pm.response.headers:HeaderList
pm.response.responseTime:Number
pm.response.responseSize:Number
pm.response.text():Function → String
pm.response.json():Function → Object
有關詳細信息,請參閱 Postman Collection SDK 響應參考。
該pm.info對象提供與請求和腳本本身相關的數(shù)據,包括名稱、請求 ID 和迭代計數(shù)。
該pm.info對象提供以下屬性和方法:
pm.info.eventName:String
pm.info.iteration:Number
pm.info.iterationCount:Number
pm.info.requestName:String
pm.info.requestId:String
該pm.cookies對象提供對與請求關聯(lián)的 cookie 列表的訪問。
該pm.cookies對象提供以下屬性和方法:
pm.cookies.has(cookieName:String):Function → Boolean
pm.cookies.get(cookieName:String):Function → String
pm.cookies.toObject():Function → Object
有關詳細信息,請參閱 Postman Collection SDK Cookie 列表參考。
您還可以使用pm.cookies.jar指定域來訪問請求 cookie。
要使用這些方法啟用編程訪問pm.cookies.jar,請先將 cookie URL 添加到allowlist。
pm.cookies.jar():Function → Object
例如:
const jar = pm.cookies.jar();
//cookie methods...
jar.set(URL:String, cookie name:String, cookie value:String, callback(error, cookie)):Function → Object
jar.set(URL:String, { name:String, value:String, httpOnly:Bool }, callback(error, cookie)):Function → Object
例如:
const jar = pm.cookies.jar();
jar.set("httpbin.org", "session-id", "abc123", (error, cookie) => {
if (error) {
console.error(`An error occurred: ${error}`);
} else {
console.log(`Cookie saved: ${cookie}`);
}
});
jar.get(URL:String, cookieName:String, callback (error, value)):Function → Object
jar.getAll(URL:String, callback (error, cookies)):Function
jar.unset(URL:String, token:String, callback(error)):Function → Object
jar.clear(URL:String, callback (error)):Function → Object
有關詳細信息,請參閱 Postman Collection SDK Cookie 參考。
您可以使用該方法從預請求或測試pm.sendRequest腳本異步發(fā)送請求。如果您同時執(zhí)行計算或發(fā)送多個請求,而無需等待每個請求完成,這允許您在后臺執(zhí)行邏輯。您可以通過添加回調函數(shù)來避免阻塞問題,以便您的代碼可以在 Postman 收到響應時做出響應。然后,您可以對響應數(shù)據執(zhí)行所需的任何其他處理。
您可以向該pm.sendRequest方法傳遞一個 URL 字符串,或者可以提供一個完整的 JSON 格式的請求配置,包括標頭、方法、正文等。
// Example with a plain string URL
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
} else {
console.log(response);
}
});
// Example with a full-fledged request
const postRequest = {
url: 'https://postman-echo.com/post',
method: 'POST',
header: {
'Content-Type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'this is json' })
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
});
// Example containing a test
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
}
pm.test('response should be okay to process', () => {
pm.expect(error).to.equal(null);
pm.expect(response).to.have.property('code', 200);
pm.expect(response).to.have.property('status', 'OK');
});
});
當您使用collection runner或Newman時,該postman對象提供setNextRequest構建請求工作流的方法。
請注意,當您使用Send運行請求時,這setNextRequest沒有任何效果;它僅在您運行集合時有效。
當您運行一個集合(使用集合運行器或 Newman)時,Postman 將以默認順序或您在設置運行時指定的順序運行您的請求。但是,您可以使用postman.setNextRequest指定下一個要運行的請求來覆蓋此執(zhí)行順序。
postman.setNextRequest(requestName:String):Function
postman.setNextRequest(requestId:String):Function
例如:
//script in another request calls:
//pm.environment.set('next', pm.info.requestId)
postman.setNextRequest(pm.environment.get('next'));
用于pm.visualizer.set指定模板以在 Postman Visualizer 中顯示響應數(shù)據。
pm.visualizer.set(layout:String, data:Object, options:Object):Function
用法示例:
var template = `<p>{{res.info}}</p>`;
pm.visualizer.set(template, {
res: pm.response.json()
});
用于pm.getData檢索 Postman Visualizer 模板字符串中的響應數(shù)據。
pm.getData(callback):Function
回調函數(shù)接受兩個參數(shù):
用法示例:
pm.getData(function (error, data) {
var value = data.res.info;
});
您可以使用在預請求或測試pm.test腳本中編寫測試規(guī)范。測試包括名稱和斷言——Postman 將輸出測試結果作為響應的一部分。
該pm.test方法返回pm對象,使調用可鏈接。以下示例測試檢查響應是否有效以繼續(xù)。
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');
});
可以將可選的done回調傳遞給pm.test, 以測試異步函數(shù)。
pm.test('async test', function (done) {
setTimeout(() => {
pm.expect(pm.response.code).to.equal(200);
done();
}, 1500);
});
pm.test.index():Function → Number
該方法允許您使用ChaiJS expect BDDpm.expect語法在響應數(shù)據上編寫斷言。
pm.expect(assertion:*):Function → Assertion
您還可以使用pm.response.to.have.*和pm.response.to.be.*來構建您的斷言。
有關更多斷言,請參閱測試示例。
require(moduleName:String):function → *
該require方法允許您使用沙箱內置庫模塊。下面列出了可用庫的列表以及相應文檔的鏈接。
以下 NodeJS 模塊也可在沙箱中使用:
要使用庫,調用方法require,將模塊名稱作為參數(shù)傳遞,并將方法的返回對象分配給變量。
您可以使用Postman 實用程序以多種方式使用測試將 Postman 構建到您的開發(fā)項目中。
更多建議: