Search code examples
testingpostmanintegration-testing

How can I check if array has an objects in Postman


I have a response the array with objects like this:

[
    {
        "id": 1,
        "name": "project one"
    },
    {
        "id": 2,
        "name": "project two"
    },
    {
        "id": 3,
        "name": "project three"
    }
]

Have can I check if my responsed array have an object { "id": 3, "name": "project three" } for example? I am trying to check by this way but it didn't work:

pm.test('The array have object', () => {
    pm.expect(jsonData).to.include(myObject)
})

Solution

  • 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);

    Use one of the ways while asserting in Postman.