Is there a way to test both 200 or 400 API status responses in the same test?
Let’s say you have a login endpoint that takes an email and a password. If the credentials are correct it returns 200, but if they aren’t it returns 400. This means the login endpoint’s body needs different data and I don’t know how to handle it in the same request (as in Postman).
So far I’ve created two requests with different bodies, but I think there might be a better approach.
What are the best options for this? To test multiple cases for a request?
The username and password would be fed into the request and then I’d put some code in the test tab like;
let z = pm.iterationData.get('expectedResponse');
if (z == "PASS") {
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
} else if (z == "FAIL") {
pm.test("Status code is 400", function () {
pm.response.to.have.status(400);
});
}
Once set up, run in collection runner and check the outputs;
I left the 400 as a fail but if the credentials actually failed then the response would be the expected 400 code.
In my case whenever I want to test with different data in request body I generally run a loop and send them in the Pre-request script then run it.
But yes this is possible only if you have few sets of data as it is the case right now for you.
I’m giving a sample code for what I do.
You can create a loop by setting a collection variable with your test data and then using a pre-request script and the JavaScript array.shift() method to get the first record from the array. (The shift method also deletes that record from the array).
You can then retrieve the various elements from the current record and set them as collection variables to be used in the actual request.
You also need to re-save the updated array over the top of the existing collection variable (which should now have one less record).
In the tests tab. You retrieve the array again which will be used in an IF statement in conjunction with pm.setNextRequest() to keep running the same request while the length of the array is more than zero.
Please note that setNextRequest() still requires the collection runner to work. You can’t get this to loop without the collection runner. Both the CSV method and the setNextRequest() method require the collection runner.
Here are a few topics that are utilizing this method.