【问题标题】:Check property of a nested element - Postman test检查嵌套元素的属性 - 邮递员测试
【发布时间】:2020-06-19 00:19:47
【问题描述】:

请协助从邮递员的 JSON 响应中获取嵌套元素的属性类型。以下是我在 POST 后的回复。

{
    "MyList": [
        [
            {
                "id": 1,
                "name": "Test"
            }
        ]
    ]
}

我想检查 name 和 id 属性是否是数字和字符串类型。以下是我的代码,但出现错误:无法读取undefined 的属性“0”。

 pm.test("Check schema and datatype", () =>{
    var jsonData = pm.response.json();

    pm.expect(typeof(jsonData[0].id)).to.eql('number');
    pm.expect(typeof(jsonData[0].name)).to.eql('string');
 })

【问题讨论】:

  • 您希望 jsonData 是对象列表,但这里 jsonDataundefined 类型,而不是对象列表。
  • 感谢您的回复@shayanrokrok,我将如何通过这个问题:(
  • 您可以检查谁应该填写 jsonData 或输入一个有问题的 sn-p 代码,显示谁应该填写对象列表的jsonData
  • 那么基本上就没有其他办法可以查看上面响应输出的属性了吗? @shayanrokrok
  • 您应用的此修改使您的问题变得更好。首先检查pm.response。也许响应无法从 JSON 转换。

标签: arrays json api postman postman-testcase


【解决方案1】:

虽然你的response body 对我来说有点奇怪,但你可以创建一个测试来检查这些数据类型,如下所示:

pm.test("Check schema and datatype", () => {
    let jsonData = pm.response.json();

    pm.expect(jsonData.MyList[0][0].id).to.be.a('number');
    pm.expect(jsonData.MyList[0][0].name).to.be.a('string');
})

这是使用 chai a 方法:

https://www.chaijs.com/api/bdd/#method_a

编辑

要检查数组中对象的大小或数量,可以使用:

pm.test("Verify number of records returned", () => { 
    let jsonData = pm.response.json().MyList[0]
    pm.expect(jsonData.length).to.equal(1);
});

【讨论】:

  • 嗨,我将如何计算为上述响应返回的记录?我现在有这样的东西,但似乎不起作用。 pm.test("验证返回的记录是 31", () => { var jsonData = JSON.parse(responseBody); var size = jsonData.length; console.log(size); pm.expect(size).to .equal(31); });
  • 我已经编辑了答案以检查数组中的对象数量。你真的应该为此打开一个单独的问题。
猜你喜欢
  • 1970-01-01
  • 2020-01-04
  • 2015-09-18
  • 2020-10-10
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多