Test fail due assertion problem

I have problem relating to assertion during practicing.

I have response body like:

[
{
“id”: 1,
“manufacturer”: “Ford”,
“model”: “Model T”,
“build”: 1927
},
{
“id”: 2,
“manufacturer”: “Tesla”,
“model”: “Model 3”,
“build”: 2017
},
{
“id”: 3,
“manufacturer”: “Tesla”,
“model”: “Cybertruck”,
“build”: 2019
}
]

I wrote test:

const response = pm.response.json()

let model;

for (let filter of response) {
if (filter.model === “Model 3”) {
//console.log(filter)
model = filter;
}
}
console.log(model)

pm.test(“car model is Model 3”, function () {
pm.expect(response.model).to.eql(“Model 3”);
});

Unfortunately, my test fail AssertionError: expected undefined to deeply equal ‘Model 3’ I was trying to figure out but dunno why this is not passing because my navigation to that model is correct. Can you guide me what is wrong with my code please

Hi szczawik,

Welcome to postman community :slight_smile:

I tried the response you pasted seems like response is invalid, but what i can suggest you is since you response is array of objects.
Try first

console.log(response)
then try console.log(response[0][2].model)
if this gives you some model in console then try to loop it.

1 Like

@szczawik Welcome to the Community :partying_face:

When I started with Postman, parsing of the JSON response was so new to me. Later I found this https://jsonpathfinder.com/. I wrote a blog about this here.

In your case, it should be

response[1].model

Try exploring this tool. Also in your snippet you have used filter method. So are you trying to compare the response directly against the value or you need to filter the model 3 and trying to validate that against your expected value (Model 3). In that case I did minor tweaks to your snippet as below:

const response = pm.response.json()

let model;

for (let filter of response) {
if (filter.model === "Model 3") {
//console.log(filter)
model = filter.model;

}
}
//console.log(model);

pm.globals.set("modelName", model);

pm.test("car model is Model 3", function () {
    pm.expect(pm.globals.get("modelName")).to.eql("Model 3");

});

Else you can directly validate the response against the expected value:

const response = pm.response.json()

pm.test("car model is Model 3", function () {
    pm.expect(response[1].model).to.eql("Model 3");

});

It depends on your requirement.

@skandh-15 Hello :wave:

The JSON error in his sample response response is due to the improper quotes. You need to validate the JSON using any online tool.

@szczawik So before providing the JSON response/snippets please surround them using back ticks :raised_hands:

I hope this helps :blush: