首页 > 解决方案 > 如何在 Postman 中循环函数

问题描述

我试图编写测试每个集合中每个元素的存在。例如:是否familyName存在于每个集合中,或者firstName存在于每个集合中,等等。

当我尝试to.have.property在循环中使用函数时(如下所示),我收到消息don't use function inside the loop

var jsonData = pm.response.json();
totalNumber = jsonData.length;

while (i < totalNumber) {
    i=0;
    pm.test('familyName is present in the response', function() {
        pm.expect(jsonData[i]).to.have.property('agentSSN');
        i++;
    }
)};

响应样本:

[
    {
        "familyName": "123",
        "firstName": "tester2",
        "middleName": "",
        "lastName": "test ",
        "ContactNumber1": "",
        "ContactNumber2": ""
    },
    {
        "familyName": "123",
        "firstName": "tester1",
        "middleName": "",
        "lastName": "test2",
        "ContactNumber1": "",
        "ContactNumber2": ""
    }

]

标签: postman

解决方案


你可以试试这个:

pm.test('familyName is present in the response', () => {
    _.each(pm.response.json(), (item) => {
        pm.expect(item).to.have.property('agentSSN');
    })
})

它将遍历响应并检查它property是否在对象中。


推荐阅读