【问题标题】:Facing some issue to print the API response values in one sentence一句话打印API响应值面临一些问题
【发布时间】:2018-08-07 22:38:42
【问题描述】:

我正在尝试断言并打印响应,因为需要帮助。

以下是响应正文:

{  
   "createdIncidents":[  
      {  
         "incidentRef":"I0000000",
         "personName":"API API",
         "personType":"Patient"
      },
      {  
         "incidentRef":"I0000000",
         "personName":"Ballarat HelpDesk",
         "personType":"Staff"
      },
      {  
         "incidentRef":"I0000000",
         "personName":"test api",
         "personType":"Visitor"
      },
      {  
         "incidentRef":"I0000000",
         "personName":null,
         "personType":"Hazard"
      }
   ]
}

我正在尝试将incidentRefpersonType 一起打印在一个字符串中。

为此,我正在使用以下代码:

var data = JSON.parse(responseBody);
data.createdIncidents.forEach(function(incident, personT) {
    var personType = "personType" + personT.personType;
    var incidents = "incidentRef" + incident.incidentRef;
    var pt = tests["incidents created for " + personType ] = 'personType';
    var inc = tests["incidents number is " + incidents] = 'incidents';
    tests["incidents created for" +inc && + pt ];
});

这里没有读取函数内的第二项。
在单独的函数声明中它工作正常。

我想打印成:

"incidentRef": "I0000000 is created for "personType": "Hazard""

【问题讨论】:

  • 回答这个问题真的很令人困惑 - 你只想注销personTypeincidentRef 吗?你想检查什么?
  • 我想断言响应并将其显示为 "incidentRef": "I0000000 is created for "personType": "Hazard" ,用于上面给出的响应
  • 我已更新我的答案以打印出您想要的内容。

标签: api response postman


【解决方案1】:

这会将 createdIncidents 数组中的每个项目记录到控制台 - 但不确定您实际尝试断言的内容:

_.each(pm.response.json().createdIncidents, (arrItem) => {
    console.log(`Incident Ref: ${arrItem.incidentRef} is created for Person Type: ${arrItem.personType}`)
})

鉴于您的响应数据,这将是输出:

Incident Ref: I0000000 is created for Person Type: Patient
Incident Ref: I0000000 is created for Person Type: Staff
Incident Ref: I0000000 is created for Person Type: Visitor
Incident Ref: I0000000 is created for Person Type: Hazard

这可以包装在 pm.test() 中,并且可以使用 pm.expect() 语法断言不同的项目。

这是非常基本的并且非常硬编码,但它会检查您示例中的数据:

pm.test('Check the response', () => {
    _.each(pm.response.json().createdIncidents, (arrItem) => {
        pm.expect(arrItem.incidentRef).to.equal("I0000000")
        pm.expect(arrItem.personType).to.be.oneOf(['Patient','Staff','Visitor','Hazard'])
        console.log(`Incident Ref: ${arrItem.incidentRef} is created for Person Type: ${arrItem.personType}`)
    })
})

【讨论】:

  • DANNY- 谢谢你的帮助,还有一件事,比如 Incident Ref: number 每次都会改变,阅读它并像上面一样打印,脚本是什么
  • 结果将始终以您想要的方式注销到控制台,检查非常不稳定,因为如果 ref Id 不同或类型不在列表中,它将失败。我对您的实施知之甚少,无法告诉您需要检查的每条数据的确切“答案”。这有望为您提供一个起点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多