如何解决如何断言数组中的数组?
有人可以帮我在邮递员的数组中断言数组吗?
我有这样的代码安宁:
"documents": [
{
"fileName": "file01_guid.pdf","documentType": "document","parentFiles": [
"file01.pdf"
]
},{
"fileName": "file02_guid.pdf","parentFiles": [
"file01.pdf"
]
}
我需要使用这种方法来断言“ParentFiles”数组:
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)
}
所以我可以编写这种测试:
{
pm.expect(array).to.include("file01.pdf","file01.pdf");
});
提前致谢
解决方法
您可以通过简单的过滤和检查长度来验证 "file01.pdf"
是否存在。您还可以通过减少来更有效地构建您的 array
。
const json_response = {
"data": {
"documents": [{
"fileName": "file01_guid.pdf","documentType": "document","parentFiles": ["file01.pdf"]
},{
"fileName": "file02_guid.pdf","parentFiles": ["file01.pdf"]
}]
}
};
const array = json_response.data.documents.reduce((acc,doc) => {
const { fileName,documentType,parentFiles: [ pfName ] } = doc;
return [ ...acc,fileName,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; }
如果只想比较数组,可以尝试以下操作:
const json_response = {
"data": {
"documents": [{
"fileName": "file01_guid.pdf","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; }
您可以使用 foreach 循环并比较值
quote
如果您只想比较两个数组,则:
//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])
})
lodash isEqual 可用于比较两个对象,如数组
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。