let resp = {};
// This is because if you try to do `JSON.parse` on a response
// which is not a JSON then it'll throw an error
try {
resp = pm.response.json();
}
catch (e) {}
pm.test(`response code should be ${pm.response.code} based on email availability`, function () {
if (_.get(resp, 'email')) { // Using lodash which is built-in postman
pm.response.to.have.status(200);
}
else {
pm.response.to.have.status(404);
}
});
There can be multiple ways to do things like these, based on what youβre checking.
But yes, you can use the entire power of javascript to do things like these.
I also used lodash which is built-into postman.
There are multiple other libraries that are built-in with postman and you can use them in the pre-request / test scripts.
What you could do is set the expected status code as Environment variable, and have the prerequest script fill it with the expected value according to how your request looks: IE
This is almost the same code as @singhsivcan suggested but then using the request instead of the response.
var req = JSON.parse(pm.request.body.raw);
if (_.get(req, 'email')) {
pm.environment.set("expectedstatus", (200));
} else {
pm.environment.set("expectedstatus", (400));
}
then have your test check the response status against (pm.environment.get(βexpectedstatusβ));