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 @jetison :

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

2 Likes