1

我的请求正文中的 JSON 原始数据中几乎没有必要的参数,我想在 Postman 的预请求脚本中验证这些参数是否存在于正文中。

{
  "stores": [
    {
      "city": "Tokyo",
      "name": "Church Street"
      ....
      ....
    }
  ]
}

如何在请求正文中检查是否city通过name

4

2 回答 2

1

您可以将该pm.test函数pm.expectPre-request Scripts.

由于 Postman 带有 Lodash,您可以使用沙箱中的_.get()函数从stores数组中获取数据。您需要在函数JSON.parse()中正确分配请求正文中的数据_.get()

let requestBody = _.get(JSON.parse(pm.request.body.raw), 'stores[0]')

pm.test("Check Body", () => {
    pm.expect(requestBody).to.have.keys(['city', 'name'])
})

或者像这样没有 Lodash 的东西:

let requestBody = JSON.parse(pm.request.body.raw)

pm.test("Check Body", () => {
    pm.expect(requestBody.stores[0]).to.have.keys(['city', 'name'])
})

有关 API的更多信息pm.*可以在这里找到:

https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/

于 2020-04-07T08:12:10.663 回答
0

使用pm.test您可以在运行结果中看到的请求正文、内容类型、响应内容。导出结果有太多细节。

测试请求正文:

pm.test(JSON.parse(pm.request.body));

使用请求正文测试 URLEncoded:

pm.test(JSON.stringify(pm.request.body.urlencoded.toObject(true)));

在请求正文中测试原始文本:

 pm.test(JSON.parse(pm.request.body.raw));

例子:

var reqBody = request.data; //JSON.parse(request.data);
tests["Data"] = reqBody.stores[0].city !== null;
于 2020-04-07T07:39:14.817 回答