Check if object exists in array in response body before performing test

Hi all,

I want to check if the language returned in the different objects of the response body is the same as the accept-language in the request headers. Not all objects are required so if an object is not present in the response body, I want the test to be skipped.

When the object I check is not part of an array, I use following test:

var jsonData = pm.response.json();
var language = pm.request.headers.get(‘Accept-Language’);

if (jsonData.recipe.title) {
pm.test(“Recipe title language equals accept-language”, function () {
pm.expect(jsonData.recipe.title.lang).is.to.equal(language);
});
} else {
pm.test.skip(“Recipe title does not exist”, function () {
});
};

However, this does not work when the object I want to check is part of an array, for example in this situation:

if (jsonData.recipe.lines.ingredient){
pm.test(“Line ingredient name language equals accept-language”, function () {
jsonData.recipe.lines.forEach(function(line){
line.ingredient.name.forEach(function(name){
pm.expect(name.lang).is.to.equal(language);
});
});
});
}
else {
pm.test.skip(“Line ingredient name does not exist”, function () {
})
};

How can I change

if (jsonData.recipe.lines.ingredient)

so that it checks if ingredient is present within the lines array?

Thank you very much for your feedback,
Tine

Change the assertion from to.equal to includes.

pm.expect(array).to.include('string');

When posting code, can you please use the performatted text option in the editor or all of the code is aligned to the left and is hard to read.

It’s also useful to post example responses.