如何检查数组是否有Postman中的对象

643ylb08  于 12个月前  发布在  Postman
关注(0)|答案(3)|浏览(224)

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

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

字符串
例如,我可以检查我的响应数组是否有对象{“id”:3,“name”:“project three”}吗?我试图通过这种方式检查,但它不起作用:

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

8oomwypt

8oomwypt1#

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

  • Array.filter()
  • 数组.find()
  • 数组.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中Assert时使用其中一种方法。

ljo96ir5

ljo96ir52#

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

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#some

*注意:Postman在沙箱中工作,仅支持以下库:

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

piztneat

piztneat3#

你也可以使用to.deep.include语法。在你的例子中,它看起来像这样:

pm.test('The array have object', () => {
    pm.expect(jsonData).to.deep.include({ id: 2, name: "project two" })
    pm.expect(jsonData).to.deep.include({ id: 3, name: "project three" })
    pm.expect(jsonData).to.deep.include({ id: 1, name: "project one" })
})

字符串

相关问题