Search code examples
postmanpostman-testcase

Can not check the JSON value from the response body


I just started testing the api using the postman. I have come across one problem with the json path..

in json file I have code which looks like this


{
 "users": [
   {
     "firstName": "UserOne",
     "lastName": "One",
     "subjectId": 1,
     "id": 1
   },
   {
     "firstName": "UserTwo",
     "lastName": "Two",
     "subjectId": 2,
     "id": 2
   },
   {
     "firstName": "UserThree",
     "lastName": "Three",
     "subjectId": 3,
     "id": 3
   }
 ],
 "subjects": [
   {
     "id": 1,
     "name": "SubOne"
   },
   {
     "id": 2,
     "name": "SubTwo"
   },
   {
     "id": 3,
     "name": "SubThree"
   }
 ]
}

I start the json server with json-server --watch db.json

After that I send GET request using postman Request URL http://localhost:3000/users

this is the body I get

[
    {
        "firstName": "UserOne",
        "lastName": "One",
        "subjectId": 1,
        "id": 1
    },
    {
        "firstName": "UserTwo",
        "lastName": "Two",
        "subjectId": 2,
        "id": 2
    },
    {
        "firstName": "UserThree",
        "lastName": "Three",
        "subjectId": 3,
        "id": 3
    }
]

I was trying to verify the firstName from the id 1 using the snippet code below

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.users[0].firstName).to.eql('UserOne');
});

But the output was FAIL Your test name | TypeError: Cannot read property '0' of undefined

I need help here because the json path users[0].firstName should give me the first index..


Solution

  • There is no key users in your response, so when you try to access the non-existed key, you will get error Cannot read property 'xxx' of undefined. To fix that, you just need:

    pm.test("Your test name", function () {
        var jsonData = pm.response.json();
        pm.expect(jsonData[0].firstName).to.eql('UserOne');
    });