在执行接口测试之前,我们需要在pre-request脚本里执行一些接口请求做一些准备工作,比如要删除某个订单,则需要确认在删除之前这个订单是存在的,那我们就可以在pre-request里判断是否存在订单,不存在则创建一个订单。
我们由浅入深的由几个例子来说明如何使用。
1. 发送一个简单的get请求
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
2. 发送一个制定headers的get请求
pm.sendRequest({
url: "https://postman-echo.com/get",
method: "GET",
header: {
"Host": "postman-echo.com",
"Accept-Encoding": "gzip, deflate, b"
}
}, function (err, response) {
console.log(response.json())
});
3. get请求里的内容使用变量
pm.sendRequest({
url: "https:" + pm.environment.get("host") + "/get",
method: "GET",
header: {
"Host": "postman-echo.com",
"Accept-Encoding": "gzip, deflate, b"
}
}, function (err, response) {
console.log(response.json())
});
4. 满足某个条件后发送第二个get请求 (接口同步)
pm.sendRequest({
url: "https://postman-echo.com/get",
method: "GET",
header: {
"Host": "postman-echo.com",
"Accept-Encoding": "gzip, deflate, b"
},
}, function (err, response) {
console.log(response.json())
//if response not empty, then call request again
if(response.json()!={}){
pm.sendRequest({
url: "https://postman-echo.com/get",
method: "GET",
header: {
"Host": "postman-echo.com",
"Accept-Encoding": "gzip, deflate, b"
}
}, function (err, response) {
console.log(response.json())
});
}
});
5.发送post请求
pm.sendRequest({
url: "https://postman-echo.com/post",
method: "POST",
header:'headername1:value1',
body: {
foo: 'thisisfoovalue'
}
}, function (err, response) {
console.log(response.json())
});
有时候发现body传不过去,可以尝试使用mode 'raw',如下图:
pm.sendRequest({
url: "https://postman-echo.com/post",
method: "POST",
header:'headername1:value1',
body: {
mode: 'raw',
raw: JSON.stringify({ foo: 'thisisfoovalue' })
}
}, function (err, response) {
console.log(response.json())
});
也可以尝试把请求的内容单独拿出来定义:
const echoPostRequest = {
url: 'https://postman-echo.com/post',
method: 'POST',
header: 'headername1:value1',
body: {
mode: 'raw',
raw: JSON.stringify({ foo: 'thisisfoovalue' })
}
};
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
});