1

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

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

如果它们是数字和字符串类型,我想检查名称和 id 属性。以下是我的代码,但出现错误:无法读取属性 '0' of undefined.

 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');
 })
4

1 回答 1

0

尽管您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');
})

这是使用 chaia方法:

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);
});
于 2020-03-07T09:22:00.543 回答