如何使用邮递员查找API响应中返回的节点数?

时间:2018-01-22 07:41:09

标签: javascript testing automated-tests postman functional-testing

假设以下是API响应:

{
    "content": 
    [
        {
            "id": 90008,
            "capacity": 2,
            "manufacturer": "NISSAN",
            "model": "Sunny",
            "comment": "Nice Compact car.",
            "features": {
                "high_grade": false,
                "normal_grade": true
            },
            "images": [
                {
                    "type": "OUTSIDE",
                    "url": "http://some-image-1.jpg"
                },
                {
                    "type": "INSIDE",
                    "url": "http://some-image-2.jpg"
                }
            ],
            "links": []
        },
        {
            "id": 90009,
            "capacity": 7,
            "manufacturer": "Audi",
            "model": "Q7",
            "comment": "Very good leg space!",
            "features": {
                "high_grade": true,
                "normal_grade": false
            },
            "images": [
                {
                    "type": "OUTSIDE",
                    "url": "http://some-image-1.jpg"
                },
                {
                    "type": "INSIDE",
                    "url": "http://some-image-2.jpg"
                }
            ],
            "links": []
        }
    ],
    "page": {
        "size": 20,
        "total_elements": 2,
        "total_pages": 1,
        "number": 0
    }
}

现在在postman中,我怎么知道内容中返回的父/主节点总数是8,如下所示:

  1. ID
  2. 容量
  3. 制造商
  4. 模型
  5. 评论
  6. 功能
  7. 图像
  8. 链接
  9. 我尝试了以下但失败了:

    pm.test("Check total no. of nodes in all content is 8", () => {
        for (i = 0; i < jsonData.content.length; i++) { 
            pm.expect(Object.keys(jsonData.content[i]).length).to.equal(8);
        }
    });
    

1 个答案:

答案 0 :(得分:1)

您的代码遗失了:

var jsonData = pm.response.json()

测试会在运行时告诉您,并向您发送Check total no. of nodes in all content is 8 | ReferenceError: jsonData is not defined消息。

所以看起来应该是这样的:

pm.test("Check total no. of nodes in all content is 8", () => {
    var jsonData = pm.response.json()
    for (i = 0; i < jsonData.content.length; i++) { 
        console.log(Object.keys(jsonData.content[i]))
        pm.expect(Object.keys(jsonData.content[i]).length).to.equal(8);
    }
});

您提到了The 0 indexed nodes, such as links, can be ignored,但您的测试方式以及您要检查的内容无论如何都会包含它们。它们也是您附加到问题列表中的一部分。

我添加了一行console.log(Object.keys(jsonData.content[i])),以便在邮递员控制台中向您展示。

Console Output