使用 javascript 和 Postman 计算 JSON 数组中的记录

Counting records in JSON array using javascript and Postman

我有一个控件 returns 2 条记录:

{
  "value": [
    {
      "ID": 5,
      "Pupil": 1900031265,
      "Offer": false,
    },
    {
      "ID": 8,
      "Pupil": 1900035302,
      "Offer": false,
      "OfferDetail": ""
    }
  ]
}

我需要通过 Postman 进行测试,我有 2 条记录 returned。我尝试了在这里和其他地方找到的各种方法,但没有成功。使用下面的代码无法 return 预期的答案。

responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = list === undefined || list.length === 2;

此时我不确定是 API 我正在测试的错误还是我的编码 - 我已经尝试遍历 returned 的项目,但那不起作用对我来说也是。请有人建议 - 我是 javascript 的新手,所以我希望我的问题有一个明显的原因,但我没有看到它。非常感谢。

你的响应体是一个对象你找不到对象的长度试试

var list = responseJson.value.length;

如评论中所述,您应该测试responseJson.value.length

responseJson = JSON.parse(responseBody); tests["Expected number"] = typeof responseJson === 'undefined' || responseJson.value.length;

更正您的 json。试试这个。

=======================v

var test = JSON.parse('{"value": [{"ID": 5,"Pupil": 1900031265,"Offer": false},{"ID": 8,"Pupil": 1900035302,"Offer": false,"OfferDetail": ""}] }')
    
test.value.length; // 2

所以需要识别json中的数组(从[括号开始。然后取key再查[=13=的length ].

在邮递员中,在 Tests 部分下,执行以下操作(下面的屏幕截图): var body = JSON.parse(responseBody); tests["Count: " + body.value.length] = true;

这是您应该看到的内容(注意:我将 responseBody 替换为 JSON 以模拟上面的示例):

我遇到了类似的问题,我用来测试一定数量的数组成员的是:

responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;

要检查您获得的值,打印它并检查 postman 控制台。

console.log(responseJson.length);

我在验证 JSON 中数组的长度时遇到了类似的问题。以下代码段应该可以帮助您解决问题-

responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = responseJson.value.length === list;

工作代码

 pm.test("Verify the number of records",function()
 {
   var response = JSON.parse(responseBody); 
   pm.expect(Object.keys(response.value).length).to.eql(5);

 });
//Please change the value in to.eql function as per your requirement    
//'value' is the JSON notation name for this example and can change as per your JSON

这是我统计记录的方法

//parsing the Response body to a variable
    responseJson = JSON.parse(responseBody);

//Finding the length of the Response Array
    var list = responseJson.length;
    console.log(list);
    tests["Validate service retuns 70 records"] = list === 70;

首先,您应该将响应转换为 json 并找到值路径。值为数组。您应该调用 length 函数来获取其中有多少个对象并检查您的预期大小

pm.test("Validate value count", function () {
    pm.expect(pm.response.json().value.length).to.eq(2);
});

这是我找到的最简单的方法:

pm.expect(Object.keys(pm.response.json()).length).to.eql(18);

无需为您的变量自定义任何内容。只需复制、粘贴“18”并将其调整为您期望的任何数字。

断言数组中只有 2 个对象的更新版本:

pm.test("Only 2 objects in array", function (){
    pm.expect(pm.response.json().length).to.eql(2);
});