Considering the following example.
for (let i = 1; i < 11; i++) {
const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
pm.test(`Request ${i} - status code is 200`, () => {
pm.expect(response).to.have.status(200);
let resJson = response.json();
console.log(resJson.args.test);
});
};
pm.sendRequest now supports top-level awaits. So this works fine as the sendRequest is outside of any functions, and the sendRequests all come out in the correct order.
This would be a typical scenario and this works fine.
However, I would like to move the sendRequest so its within the test block.
The scenario behind this is to run multiple sendRequests() in order, but to stop processing the script if the test related to the first request fails.
I donβt think the pm.test function is async, so Iβm wondering if there is a way to get around this in JavaScript.
If you do the following, you get a syntax error.
for (let i = 1; i < 11; i++) {
pm.test(`Request ${i} - status code is 200`, () => {
const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
pm.expect(response).to.have.status(200);
let resJson = response.json();
console.log(resJson.args.test);
});
};
SyntaxError: await is only valid in async functions and the top level bodies of modules
If you do the following, it removes the error, but the requests are no longer in order.
for (let i = 1; i < 11; i++) {
pm.test(`Request ${i} - status code is 200`, async () => {
const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
pm.expect(response).to.have.status(200);
let resJson = response.json();
console.log(resJson.args.test);
});
};
What Iβm really trying to do is to prevent parsing a response when there is an error.
This also works in a fashion.
async function sendRequest(request, i) {
try {
const response = await pm.sendRequest(request);
pm.test(`Request ${i} - status code is 200`, () => {
pm.expect(response).to.have.status(200);
});
return {
'data': response,
'status': "success"
};
} catch (error) {
console.log(error);
pm.test(`Request ${i} - status code is 200`, () => {
pm.expect(error, error.code).to.be.undefined;
});
return {
"status": "error",
"errorcode": error.code
}
}
};
for (let i = 1; i < 11; i++) {
let response = await sendRequest(`https://postman-echo.com/get?test=request${i}`, i);
if (response.status === "success") {
console.log(response.data.json().args.test); // Postman Echo Response
}
};
Posing the question here first before I post the same on StackOverflow.
@danny-dainton Perhaps one for Udit to have a look at if he has the time.
I either need to get access to the error variable that you could get when you send a normal sendRequest or I would like to run the await version within the test function so I can deal with errors in a more refined manner.