postman #
Environments #
Pre-request Script[1] #
const lastResponseStatus = pm.environment.get('lastResponseStatus')
if (lastResponseStatus != 200) {
const accountId = pm.environment.get('accountId')
const data = {
account: '',
password: '',
accountId
}
const openapi_business_domain = pm.environment.get('openapi-business')
const loginRequest = {
url: `https://${openapi_business_domain}/v2/login`,
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'raw',
raw: JSON.stringify(data)
}
}
pm.sendRequest(loginRequest, (err, res) => {
if (err) {
console.log(err)
}
else {
const jsonData = res.json()
pm.environment.set('X-Access-Token', jsonData.accessToken)
}
})
}
Tests #
pm.environment.set('lastResponseStatus', pm.response.code)
请求 API #
Case #
使用 Environment、Pre-request Script 注入请求参数 #
测试 API 时需要 mock 一个随机字符串
pre-request script 代码[2]:
let randomId = (new Date()).toISOString() + Math.random().toString(36).slice(-8);
pm.environment.set('randomId', randomId);