AssertionError: expected undefined to be a string - getting this error

[
{
“id”: “1”,
“name”: “John”,
“location”: “india”,
“phone”: “1234567890”,
“courses”: [
“java”,
“selenium”
]
},

pm.test(“Testdata validation” , () =>
{
const jsonData = pm.response.json();
pm.expect(jdata).to.be.an(“object”);
pm.expect(jsonData.location).to.be.a(“string”);

});

Your response is an array with a single object in.

So you have to reference the array by its index. Array indexes start at zero.

pm.expect(jsonData[0].location).to.be.a(“string”);

thanks it worked,

what about incase of multiple objects
[
{
“id”: “1”,
“name”: “John”,
“location”: “india”,
“phone”: “1234567890”,
“courses”: [
“java”,
“selenium”
]
},
{
“name”: “Raunak”,
“location”: “india”,
“phone”: “98876543213”,
“courses”: [
“python”,
“appium”
],
“id”: “2”
},
{
“id”: “3”,
“name”: “Smith”,
“location”: “Canada”,
“phone”: “165498765”,
“courses”: [
“C#”,
“RestAPI”
]
}
]

It’s all according to what you want to test.

You may have to loop though the response like in the following example.

const response = pm.response.json();
console.log(response);

response.forEach(object => {
    pm.test(`location for id${object.id} is a string`, () => {
        pm.expect(object.location).to.be.a("string");
    });
});

This is using a concept called Template Literals and in particular string interpolation to customize the test case name, otherwise you just get the same test case name for each object (which makes it hard to troubleshoot when it fails).

Template literals (Template strings) - JavaScript | MDN (mozilla.org)

The test case uses backticks, and you can include variables wrapped in ${}.

image