Possibility to test if my id is sorted in ascending order in my body

I would like to know if it is possible to test that my id is well sorted in ascending order in my body.

“_metadata”: {
“offset”: 0,
“limit”: 10,
“total”: 3,
“page”: {
“current”: 1,
“total”: 1
}
},
“data”: [
{
“id”: 1,
“description”: “EN - FARBY-LAKIERY Type 1”,
“status”: “ENABLED”,
“departmentId”: 2,
“subDepartmentId”: 1
},
{
“id”: 2,
“description”: “EN - FARBY-LAKIERY Type 2”,
“status”: “ENABLED”,
“departmentId”: 2,
“subDepartmentId”: 1
},
{
“id”: 3,
“description”: “EN - FARBY-LAKIERY Type 3”,
“status”: “ENABLED”,
“departmentId”: 2,
“subDepartmentId”: 1
}
]
}

I would like to create a test script to see that my id is sorted in ascending order.

Thank

1 Like

Using pure JavaScript and broken down in smaller pieces

pm.test("All ids are ascending", () => {
    const response = pm.response.json();

    // Extract all ids in an array
    const ids = response.data.map(item => item.id);
    
    // Check that all are ascending
    function isAscending(a) {
        return a.every((x, i) => {
            return i === 0 || x >= a[i-1];
        });
    }
    
    pm.expect(isAscending(ids)).to.be.true;
});

Simplified version

pm.test("All ids are ascending", () => {
    const response = pm.response.json();

    const isAscending = response.data.map(item => item.id).every((current, index, ids) => index === 0 || current >= ids[index-1]);
    
    pm.expect(isAscending).to.be.true;
});

P.S. Test and make sure the tests actually fail when needed.

2 Likes

Thanks to you ! It works very well. I was able to test that the tests really fail when needed. :grinning:

2 Likes