const invalidinput = pm.response.json();
const successfulorder=pm.response.json();
if(pm.response.to.have.status(400)){
pm.test("validation of when input body is empty or invalid", function(){
console.log(invalidinput);
pm.expect(invalidinput.error).to.eql("Invalid or missing bookId.");
})
}
else{
pm.test("validation of json response for successfulorder", function(){
pm.response.to.have.status(201);
pm.expect(successfulorder.created).to.eql(true);
})
}
for order post request , if the input body is not correct status will be 400, else the input body is correct and status is 200.
but when i am trying to execute with correct input body, the else block is not getting executed.
Please help me how to resolve this
pm.test("Validation when input body is empty or invalid", function() {
if (pm.response.status === 400) {
const invalidInput = pm.response.json();
console.log(invalidInput);
pm.expect(invalidInput.error).to.eql("Invalid or missing bookId.");
}
});
pm.test("Validation of JSON response for successful order", function() {
if (pm.response.status === 201) { // Note: You mentioned 200, but your test checks for 201.
const successfulOrder = pm.response.json();
console.log(successfulOrder);
pm.expect(successfulOrder.created).to.eql(true);
}
});
That’s not right, as both tests will always pass.
If the response status is 201, then the first test block will execute but not run any assertions and therefore the test will always pass.
This should be an IF statement, with an ELSE IF, and a final ELSE to capture any situations where neither blocks are triggered.
Put the tests within the IF statements, not wrapped around the IF statements.
This code will actually pass both tests every time as it should be pm.response.code, not pm.response.status, which will just return “ok” on a successful request.
The other option is to use a switch function.
Something like…
const response = pm.response.json();
let responseStatus = pm.response.code;
switch (responseStatus) {
case 400:
pm.test("Validation when input body is empty or invalid", function () {
pm.expect(response.error).to.eql("Invalid or missing bookId.");
});
break;
case 201:
pm.test("Validation of JSON response for successful order", function () {
pm.expect(response.created).to.eql(true);
});
break;
case 404:
console.log("404"); // add your test here
break;
default:
console.log("something else"); // for any unexpected codes
pm.test("Create a custom error message", function () {
pm.expect(false, 'nooo why fail??').to.be.ok;
});
}