Search code examples
apiautomationcypressunique-id

How can I validate that the response of API has unique IDs while doing API Automation?


I am using Cypress for API automation. I want to verify that the "id" of these response are unique. Below is the sample response of the API

{
 "data": 
    [
        {
            "id": 5,
            "created": "2021-01-04T03:50:03.458+05:30"
        },
        {
            "id": 7,
            "created": "2021-01-04T03:50:03.469+05:30"
        },
        {
            "id": 8,
            "created": "2021-01-04T03:50:03.474+05:30"
        }
    ]
}

Any suggestion or idea will be highly appreciated. Thank you.


Solution

  • There are more options, you can make use of Set:

    const data = {
        "data": [
            {
                "id": 5,
                "created": "2021-01-04T03:50:03.458+05:30"
            },
            {
                "id": 7,
                "created": "2021-01-04T03:50:03.469+05:30"
            },
            {
                "id": 8,
                "created": "2021-01-04T03:50:03.474+05:30"
            }
        ]
    };
    
    const ids = data.data.map(e => e.id);
    const setIds = new Set(ids);
    expect(ids.length).to.equal(setIds.size);
    

    Set will always contain only unique values, so if you don't have unique ids in the original data structure, the set object will have fewer elements.