Postman – Check multiple response codes not just the one you are expecting.

posted in: Postman, Testing | 0

When writing tests for api requests using Postman, it is really simple to fall for the “check the response code is correct” and that’s it.

What about the other codes you often see and know why they are returned. 521 server error. This would be good to know. 404 bad request. Again, another easy fix and would be good to know.

When you are running hundreds of tests at once using the Postman Runner, when one fails you want to know why it failed, not that 200 wasn’t returned. We can even expand on this and check the response. Is there actually any data returned? Is another api request in our flow reliant on this data being returned? Again, it would be good to know that data is indeed being returned.

This seems simple enough, but I am amazed to see so many requests missing this. 
Here is my basic snippet I use and expand on as and when needed:


console.log(" ");
console.log("## TEST RESPONSE CODE ##");
var erc = 200;
// This test checks if the created code is 200 or a bad request of 400. For all other codes, it assumes something went wrong.
if (responseCode.code === erc)
{
var data = JSON.parse(responseBody);
tests["The response code was " + responseCode.code + " " + responseCode.name] = responseCode.code === erc;
console.log("The response code was " + responseCode.code + " " + responseCode.name);
}
else
{
if (responseCode.code === 400)
{
tests["The response code was 400 " + responseCode.name + " - please check the body of the request as something is wrong."] = responseCode.code === erc;
console.log("The response code was 400 " + responseCode.name + " - please check the body of the request as something is wrong. ");
}
else
{
tests["The response code was " + responseCode.code + " " + responseCode.name + " something went wrong!"] = responseCode.code === erc;
console.log("The response code was " + responseCode.code + " " + responseCode.name + " something went wrong!");
}
}
console.log(" ");

You’ll also notice that the parsing of the response body is within the first “if” statement. This is to prevent an error from occurring when there is no response body to parse.

Leave a Reply