Reputation: 1181
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:
{
"customerNumber": "123",
"customCategories": [
{
"customCategoryID": "1546",
"customCategoryDesc": "7100",
"itemNumbers": [
"7205",
"1834"
]
},
{
"customCategoryID": "1547",
"customCategoryDesc": "7130",
"itemNumbers": [
"2251",
"9832"
]
},
{
"customCategoryID": "1548",
"customCategoryDesc": "7315",
"itemNumbers": [
"1225541",
"1197233"
]
},
{
"customCategoryID": "1546",
"customCategoryDesc": "7100",
"itemNumbers": [
"7205",
"1834"
]
},
]
}
As you can see, "customCategoryID": "1546" is repeated; thus I want a test to fail with this response, as well as display the repeated customCategoryID value ("1546").
I have viewed a couple of answers in this question and this question, but need to use the latest test script syntax for Postman has updated their JS library as well as have an assertion for the duplicated data.
Assistance with this is much appreciated.
Upvotes: 2
Views: 2690
Reputation: 25911
You could try something like this to check for duplicate ids:
function checkIfArrayIsUnique(array) {
return array.length === new Set(array).size;
}
pm.test('Check is Ids are unique', () => {
let ids = []
_.each(pm.response.json().customCategories, (item) => {
ids.push(item.customCategoryID)
})
pm.expect(checkIfArrayIsUnique(ids), ids).to.be.true
})
It's looping through the customCategoryID
property of each object in the customCategories
array and storing that value in the ids
array.
The checkIfArrayIsUnique
function is taking that ids
array and using the Set method to help with the comparison.
The Set method creates a new object, from the ids
array, that only contains unique values so it's checking to see if the ids
array length matches the new Sets size, this returns either true or false.
There's a basic pm.expect()
statement to check if the checkIfArrayIsUnique
function returns true, if it's not unique it will return false and fail the test.
Upvotes: 2