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

643ylb08  于 2024-01-07  发布在  Postman
关注(0)|答案(3)|浏览(351)

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

  1. [
  2. {
  3. "id": 1,
  4. "name": "project one"
  5. },
  6. {
  7. "id": 2,
  8. "name": "project two"
  9. },
  10. {
  11. "id": 3,
  12. "name": "project three"
  13. }
  14. ]

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

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

8oomwypt

8oomwypt1#

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

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

示例如下:

  1. data = [
  2. {
  3. "id": 1,
  4. "name": "project one"
  5. },
  6. {
  7. "id": 2,
  8. "name": "project two"
  9. },
  10. {
  11. "id": 3,
  12. "name": "project three"
  13. }
  14. ];
  15. let object_to_find = { id: 3, name: 'project three' }
  16. // Returns the first match
  17. let result1 = data.find(function (value) {
  18. return value.id == object_to_find.id && value.name == object_to_find.name;
  19. });
  20. // Get filtered array
  21. let result2 = data.filter(function (value) {
  22. return value.id == object_to_find.id && value.name == object_to_find.name;
  23. });
  24. // Returns true if some values pass the test
  25. let result3 = data.some(function (value) {
  26. return value.id == object_to_find.id && value.name == object_to_find.name;
  27. });
  28. console.log("result1: " + result1.id + ", " + result1.name);
  29. console.log("result2 size: " + result2.length);
  30. console.log("result3: " + result3);

字符串
在Postman中Assert时使用其中一种方法。

展开查看全部
ljo96ir5

ljo96ir52#

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

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

字符串

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

  1. pm.expect(_.some(data,{
  2. "id": 3,
  3. "name": "project three"
  4. })).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语法。在你的例子中,它看起来像这样:

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

字符串

相关问题