My else part is not getting executed when i am getting other status code(ex:400)

Hi Guys,

I am new to the postman and i have written test scripts using if else but my else part is not executing whenever i am getting different status code instead of expected one.

Can anyone help me where i am doing wrong ?

Please find the sample code which i have written for my request below.

//To capture request body name and reponse body name field’s value
let reqBody = JSON.parse(request.data);
reqName = reqBody.name;
console.log(reqName);
let resBody = JSON.parse(responseBody);
resName = resBody.name;
console.log(resName);

//To check status code and name field’s value are equal
if(pm.response.to.have.status(201) && reqName === resName) {
pm.test(‘Test is passed with Status code 201 and expected client name’);
console.log(“Test is passed”);
}
else{
pm.test(“Test is failed”);
console.log(“Test is falied”);
}

Hey, @IPGMB013 welcome to the community! :wave:

Your else part is not being executed because the assertion is probably throwing an error and your script stops executing. Also, the assertion doesn’t return a boolean -> pm.response.to.have.status(201) // this won’t return a boolean value.

The correct way to do this is, write a test:

let reqBody = JSON.parse(request.data);
reqName = reqBody.name;
console.log(reqName);
let resBody = JSON.parse(responseBody);
resName = resBody.name;
console.log(resName);


pm.test('should have the status code as 201 and reqName to equal resName', function () {
  pm.response.to.have.status(201);
  pm.expect(reqName).to.equal(resName);
});

Now when you’ll run this script, you’ll see that whenever any of these assertions throw an error, the test will fail.

There are a lot of resources around writing tests in Postman, I’ll leave a few here by @joyce :


Also, official docs:
https://learning.postman.com/docs/postman/scripts/test-scripts/

2 Likes