Search code examples
postmanpostman-collection-runnerpostman-testcase

Postman test is always passing even though it fails


While running postman Tests, Test case seems to be always passing The response body is provided below. I am trying to fetch id when the name is "Erin" and validate that id is 800. Small piece of code that i wrote is below the response body written below.FOr some reason the test always returns true. If for some reason if Erin and 800 are not present still it passes the test.

[
 {
  "id":991,
  "name":"Tomy"
 },
 {
  "id":800,
  "name":"Erin"
 }
]
Code:
pm.test("Validate id to be 800", function() {
   var jsonData = pm.response.json();
   for(int i=0; i<responseJson.length;i++){ 
      if(jsonData[i].name=='Erin'){
         pm.expect(jsonData[i].id).to.eql(800);
      }
     }
});

Updated the response a bit a below , i wanted my test to fail as "Jack" is not found and to pass only if Jack is found

pm.test("Validate id to be 800", function () {
  let jsonData = pm.response.json();
  for(i=0; i < jsonData.length; i++) { 
     if(jsonData[i].name == 'Jack') {
        pm.expect(jsonData[i].id).to.eql(800);
      }
     }
  });

Solution

  • That response body doesn't look quite right to me, I would expect to see quotes around the property keys in the objects.

    Also, your references were not named correctly and that would pass the test as it wouldn't have caused any reference errors in the scripts.

    This should help you out:

    pm.test("Validate id to be 800", function () {
       let jsonData = pm.response.json();
    
       for(i=0; i < jsonData.length; i++) { 
          if(jsonData[i].name === 'Erin') {
            pm.expect(jsonData[i].id).to.eql(800);
          }
        }
    });
    

    You could rewrite the test code to something like this:

    pm.test("Validate id to be 800", () => {
        let jsonData = pm.response.json();
    
        jsonData.forEach(item => {
            if(item.name === 'Erin') {
                pm.expect(item.id).to.eql(800);
             }
        });
    });
    

    Postman

    And the Test Results when it fails:

    enter image description here