【问题标题】:How can I check if array has an objects in Postman如何检查数组是否在邮递员中有对象
【发布时间】:2021-02-04 02:51:31
【问题描述】:

我对数组有这样的响应:

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

我可以检查我的响应数组是否有一个对象 { “身份证”:3, “名称”:“项目三” } 例如? 我正在尝试通过这种方式进行检查,但没有成功:

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

【问题讨论】:

    标签: testing postman integration-testing


    【解决方案1】:

    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 中断言时使用其中一种方式。

    【讨论】:

      【解决方案2】:

      您也可以在使用 JSON.stringify 将其转换为字符串后使用包含来验证这一点

      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

      【讨论】:

      • 如果您需要比提供的全局 _ 对象(在撰写本文时使用 3.10.1)更高版本的 lodash,您必须手动要求它:var latestLodashVersion = require('lodash');
      猜你喜欢
      • 2017-02-14
      • 2019-12-26
      • 2017-06-22
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      相关资源
      最近更新 更多