检查嵌套元素的属性-邮递员测试

时间:2020-03-06 09:28:00

标签: arrays json api postman postman-testcase

请协助从邮递员的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');
 })

1 个答案:

答案 0 :(得分: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');
})

这是使用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);
});