Postman Test - Validating String Values in an Object in an Array

How can I check if array has an objects in Postman

pm.expect(jsonData).to.include(myObject) works for String but not for Object. You should use one of the following functions and compare each property of the object:

  • Array.filter()
  • Array.find()
  • Array.some()

Examples:

data = [
{
"id": 1,
"name": "project one"
},
{
"id": 2,
"name": "project two"
},
{
"id": 3,
"name": "project three"
}
];
let object_to_find = { id: 3, name: 'project three' }

// Returns the first match
let result1 = data.find(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});

// Get filtered array
let result2 = data.filter(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});

// Returns true if some values pass the test
let result3 = data.some(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});

console.log("result1: " + result1.id + ", " + result1.name);
console.log("result2 size: " + result2.length);
console.log("result3: " + result3);

Postman - I want to check a value to be inside an array

You're trying to check the value from the array children, hence, you should not use the .totalId.children, instead you have to do is jsonData.results[0].children.

As you trying to check the value from the object of an array, you need add custom JavaScript logic to check the values of id param.

Here is the function you can use in your test script.

function _isContains(json, keyname, value) {
return Object.keys(json).some(key => {
return typeof json[key] === 'object' ?
_isContains(json[key], keyname, value) : key === keyname && json[key] === value;
});
}

The function _isContains checks the value and key name for the each object from the array.

Now you can pass needed input to the function in your test case.

pm.test("The response contains a valid id in the response", function () {
pm.expect(_isContains(jsonData.children, "id" ,"1111")).to.be.true;
});

This will check from the array of the object with the key id and value 1111, if it's available then it will returns true, otherwise returns false.


Final Test Script

var jsonData = pm.response.json();

pm.test("The response contains a valid id in the response", function () {
pm.expect(_isContains(jsonData.children, "id" ,"1111")).to.be.true;
});

function _isContains(json, keyname, value) {
return Object.keys(json).some(key => {
return typeof json[key] === 'object' ?
_isContains(json[key], keyname, value) : key === keyname && json[key] === value;
});
}

How to verify ARRAY response in POSTMAN?

pm.test("Test Case Name", function () {

var jsonData = pm.response.json();
var xyz = [{product id : 123456789}];

pm.expect(xyz).to.deep.equal(jsonData);

});


Related Topics



Leave a reply



Submit