Shams
Shams

Reputation: 61

Using Postman How to write a test to check for duplicate ids

I would like to write a test in Postman that validates there are no duplicate values in the array of objects. Here is an example response: This is my json response :

{
    "content": [
        {
            "id": "88848990-c4c8-4e7d-b708-3e69e684085b",
            "name": "UPDATED",
           
        },
        {
            "id": "42c37e1d-eed3-4f5c-b76a-7b915c05b0bf",
            "name": "Swoop ",
            
           
        },
        {
            "id": "88848990-c4c8-4e7d-b708-3e69e684085b",
            "name": "United Test Airlines",
           
        },

I can see 2 ids that are the same I want to write a test in postman to identify any duplicates in my results. If the test picks up duplicates then it must fail, if it does not pick up any duplicates it should pass. Note I am new to postman api testing.

Upvotes: 0

Views: 994

Answers (1)

lucas-nguyen-17
lucas-nguyen-17

Reputation: 5917

The short and esay solution might be:

  1. Save all id in an array
  2. Create a set from this array
  3. Compare size of the array and the set. If it equals, then no duplication. If not, there is a duplication.
const res = pm.response.json();
const ids = _.map(res.content, "id");

pm.test("check duplicate id", () => {
    const setIds = new Set(ids);
    pm.expect(ids.length).eql(setIds.size);
})

Upvotes: 1

Related Questions