Hi all,
We are working on a poc for, hopfully ,using postman as our new testing api solution.
Iβm stuck about waiting a request to execute before proceed some test inside the Tests tab. For that, two methods have been try without succes (send request and timeout, promise and await).
In the method 1, the test result is finish without waiting setTimout()
and there is no way to updated result after.
In the method 2, the Promise + await cannot be used because fo SyntaxError: await is only valid in async functions and the top level bodies of modules
Some solution exist on the forum but if we run in collection (using postman.setNextRequest() and loop plus delay).
In addition, it cannot be done before using Pre-request Script, request have to be send after the api call.
May I ask some tips, idea or work around ?
If you want to taste this case, see below an easy setup sample highlighting the problematic :
the curl to import
curl --location --request GET 'https://api.coindesk.com/v1/bpi/currentprice.json' \
--header 'Content-Type: application/json'
The test script to copy past
let idTest = request.name; // id file template
let expectedStatusCode = 200; // http status code
let expectedLatency = 2500; //ms
// dupmp api
const requestOptions = { url: `https://api.agify.io/?name=Persphone`, method: 'GET', header: { 'content-type': 'application/json' },
body: { mode: 'raw', raw: JSON.parse(pm.response.text())}
};
var method1_data ;
var method2_data;
// Method 1
pm.sendRequest(requestOptions, (err, res) => {
console.log(res.text());
method1_data = res.text()
setTimeout( function(){ console.log("(method1) simulated timout of 3s");},3000);
return res.text();
})
console.log("(method1) method1_data not waiting/timeout (unfortunalty equal undefined) :",method1_data);
setTimeout( function(){ console.log("(method1) simulated body test scitp timout of 10s");},10000);
// Method 2 Promise
async function LoadDiffFromAnotherNodeServer() {
return new Promise((resolve, reject) => {
pm.sendRequest(requestOptions, (err, res) => {
if (err) {
return reject(err);
}
setTimeout( () => {console.log("(method2) simulated timout of 5s")}, 5000);
return resolve(res);
})
});
}
LoadDiffFromAnotherNodeServer()
.then(
method2_data => console.log("(method2) method2_data not waiting/timeout (unfortunalty equal undefined) :",method2_data.body)
)
// Test
pm.test("Method 1 waitng request", function(){
setTimeout( function(){
console.log("(inside test) simulated body test scitp timout of 10s");
pm.expect(method1_data,"method1_data").to.not.equal(undefined);
},10000);
pm.expect(method1_data,"method1_data").to.not.equal(undefined);
});
pm.test("Method 2 waitng request", function(){
pm.expect(method2_data,"method2_data").to.not.equal(undefined);
});
The result :
(method1_data and method2_data should be fill with the data of pm.request but itβs undefined)
Thank you a lot in advance & take care !