Reputation: 69
Can somebody please help me to assert array in array in postman ?
I have this peace of code:
"documents": [
{
"fileName": "file01_guid.pdf",
"documentType": "document",
"parentFiles": [
"file01.pdf"
]
},
{
"fileName": "file02_guid.pdf",
"documentType": "document",
"parentFiles": [
"file01.pdf"
]
}
I need to assert the "ParentFiles" array using this method:
var array = [];
var range = (json_response.data.documents).length
for (var i = 0; i < range; i++)
{
var file = json_response.data.documents[i].fileName
var type = json_response.data.documents[i].documentType;
array.push(file)
array.push(type)
}
So I could write this kind of test:
{
pm.expect(array).to.include("file01.pdf", "file01.pdf");
});
Thank you in advance
Upvotes: 1
Views: 1365
Reputation: 19939
you can loop using foreach and compare the values
//store expected files in order
array=["file01.pdf","file01.pdf"]
//now forEach on each element
json_response.data.documents.forEach( (elem,index,arr)=>{
pm.expect(elem.parentFiles[0]).to.be.eql(array[index])
})
If you just want to compare two arrays then:
pm.expect(_.isEqual(array,array2)).to.be.true
lodash isEqual can be used to compare two object like arrays
Upvotes: 0
Reputation: 48600
You can verify if "file01.pdf"
exists by simply filtering and checking the length. You can also build your array
more efficiently by reducing.
const json_response = {
"data": {
"documents": [{
"fileName": "file01_guid.pdf",
"documentType": "document",
"parentFiles": ["file01.pdf"]
}, {
"fileName": "file02_guid.pdf",
"documentType": "document",
"parentFiles": ["file01.pdf"]
}]
}
};
const array = json_response.data.documents.reduce((acc, doc) => {
const { fileName, documentType, parentFiles: [ pfName ] } = doc;
return [ ...acc, fileName, documentType, pfName ];
}, []);
console.log(array);
// Exactly two instances of "file01.pdf" exist.
console.log(array.filter(val => val === "file01.pdf").length === 2);
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you just want to compare the arrays, you can try the following:
const json_response = {
"data": {
"documents": [{
"fileName": "file01_guid.pdf",
"documentType": "document",
"parentFiles": ["file01.pdf"]
}, {
"fileName": "file02_guid.pdf",
"documentType": "document",
"parentFiles": ["file01.pdf"]
}]
}
};
const allEqual = json_response.data.documents
.every(({ parentFiles: [ filename ] }) => filename === "file01.pdf");
console.log(allEqual);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upvotes: 1