我如何检查如果数组有一个对象在邮差



我有一个响应数组与这样的对象:

[
{
"id": 1,
"name": "project one"
},
{
"id": 2,
"name": "project two"
},
{
"id": 3,
"name": "project three"
}
]

我可以检查我的响应数组是否有一个对象{"id" 3,名称";项目三"}例如?我试图通过这种方式检查,但它没有工作:

pm.test('The array have object', () => {
pm.expect(jsonData).to.include(myObject)
})

pm.expect(jsonData).to.include(myObject)适用于String,但不适用于Object。您应该使用以下函数之一,并比较对象的每个属性:

  • Array.filter ()
  • Array.find ()
  • Array.some ()

例子:

data = [
{
"id": 1,
"name": "project one"
},
{
"id": 2,
"name": "project two"
},
{
"id": 3,
"name": "project three"
}
];
let object_to_find = { id: 3, name: 'project three' }
// Returns the first match
let result1 = data.find(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});
// Get filtered array
let result2 = data.filter(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});
// Returns true if some values pass the test
let result3 = data.some(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});
console.log("result1: " + result1.id + ", " + result1.name);
console.log("result2 size: " + result2.length);
console.log("result3: " + result3);

在Postman中使用断言的方法之一。

您也可以在使用JSON.stringify将其转换为字符串后使用include进行验证。

pm.expect(JSON.stringify(data)).to.include(JSON.stringify({
"id": 3,
"name": "project three"
}))

也可以使用lodash函数some/any:

pm.expect(_.some(data,{
"id": 3,
"name": "project three"
})).to.be.true

一些https://lodash.com/docs/3.10.1

注意:Postman在沙盒中工作,只支持以下库:

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/using-external-libraries

最新更新