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

753 views Asked by At

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.

2

There are 2 answers

0
pavelsaman On BEST ANSWER

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.

0
amillionbugs On

An idea could be to prefetch all the Ids in a before and store them into a variable and then use this variable in an expect.to.be.oneOf, for example.

A downside of this would be that if the data set that is returned is quite large, then this might cause the Test to run longer than it should.

The code below shows how this could be implemented.

Note that it targets a specific Id in the body (by doing res.body[2].id ie. it gets the 3rd item in the data). If you wanted to test the whole response then you could just map through the list again (actualIdList = res.body.map((result) => result.id);) and store that to another variable and then assert against that (using expect(actualIdList).to.include.members(idList);).

describe('API Test', () => {
  let idList;

  before('should get some data', () => {
    cy.request({
      method: 'GET',
      url: myUrl
    }).then((res) => {
      idList = res.body.map((results) => results.id);
    });
  });

  it('should validate an Id in the response', () => {
    cy.request({
      method: 'GET',
      url: myUrl,
    }).then((res) => {
      expect(res.body[2].id).to.be.oneOf(idList);
    });
  });
});