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ā);
}
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 :