【问题标题】:How to write a test for nested JSON response from enterprise application如何为来自企业应用程序的嵌套 JSON 响应编写测试
【发布时间】:2020-06-26 20:03:40
【问题描述】:

我正在尝试使用 Postman 作为测试工具来验证我们的客户是否在我们的主系统中都有一个邮寄地址。由于其结构,我无法深入研究 JSON。每个响应都是一个数组结构,只有一个“节点”,没有“头属性”可寻址。

示例 JSON:


[
  {
    "ID": "cmd_org_628733899",
    "organization": {
      "name": "FULL POTENTIAL",
      "accountStatusCode": "1",
      "accountStatusDescription": "OPEN"
    },
    "location": [
      {
        "locality": "LITTLE ROCK",
        "locationType": "MAILING"
      },
      {
        "locality": "BIG ROCK",
        "locationType": "LOCATION"
      }
    ]
  }
]

测试存在的代码:

pm.test("Check for a Mailing Address", function () {
   // Parse response body
   var jsonData = pm.response.json();

   // Find the array index for the MAILING Address
   var mailingLocationIndex = jsonData.location.map(
          function(filter) {
             return location.locationType; 
          }
    ).indexOf('MAILING'); 

   // Get the mailing location object by using the index calculated above
   var mailingLocation = jsonData.location[mailingFilterIndex];

   // Check that the mailing location exists
   pm.expect(mailingLocation).to.exist;

});

错误消息:TypeError:无法读取未定义的属性“地图”

我知道我必须迭代到外部数组中的 node(0),然后深入到嵌套的位置数组以找到一个 locationType = Mailing 的条目。

我无法通过外部数组。我是 JavaScript 和 JSON 解析的新手 - 我是一名 COBOL 程序员。

【问题讨论】:

  • 你认为你可以正确缩进你的代码吗?
  • 当然——它丢失了它的格式。道歉。
  • json 示例中的括号仍然不匹配
  • 是的 - 刚刚纠正了这一点 - 标记不喜欢 [ 与 ``` 指示代码块在同一行。
  • 感谢您的帮助。那是我缺少的部分——如何寻址/提取索引(0)——如此简单。

标签: arrays json postman postman-testcase


【解决方案1】:

什么都不知道,我会说你是这个意思

pm.test("Check for a Mailing Address", function () {
    var mailingLocations = pm.response.json().location.filter(function (item) {
        return item.locationType === 'MAILING';
    });
    pm.expect(mailingLocations).to.have.lengthOf(1);
});

您想要过滤掉所有具有MAILING 类型的位置,并且应该恰好有一个,或者至少有一个,具体取决于。

pm.response.json() 是否真的返回了您在问题中显示的对象,从我所在的位置无法判断。


在现代 JS 中,上面的内容更短:

pm.test("Check for a Mailing Address", function () {
    var mailingLocations = pm.response.json().location.filter(item => item.locationType === 'MAILING');
    pm.expect(mailingLocations).to.have.lengthOf(1);
});

【讨论】:

  • 当然!再次感谢您帮助回答我的问题并提供现代 JS 代码。
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2021-05-31
  • 2020-02-14
  • 2016-09-03
  • 1970-01-01
相关资源
最近更新 更多