首页 > 解决方案 > 无法循环浏览我的邮递员回复

问题描述

我有这个来自邮递员的 json 响应,如果数组中的键“值”< 50,我想编写一个测试以返回失败。

一旦条件不满足,它将遍历数组,它会失败

我试过这个

pm.test('Matches value', () => {
    _.each(pm.response.json(), (arrItem) => {
        if (arrItem.persID === 'personID_2') {
            throw new Error(`Array contains ${arrItem.persID}`)
        }
    })
});

我的回复

{
  "groups": [
    {
      "title": "Maids",
      "subTitle": null,
      "description": null,
      "featured": false,
      "items": [
        {
          "id": "1",
          "title": "AA",
          "subTitle": "AA",
          "thumbnail": "AA",
          "priceStartingAt": {
            "value": 50,
            "baseCurrency": "USD",
            "exchangeEnabled": true,
            "exchangeRates": {
              "aed": 3.672973
            }
          },
          "categories": [
            "Activity"
          ]
        },
        {
          "id": "2",
          "title": "BB",
          "subTitle": "BB",
          "thumbnail": "BB",
          "priceStartingAt": {
            "value": 20.01,
            "baseCurrency": "USD",
            "exchangeEnabled": true,
            "exchangeRates": {
              "aed": 3.672973
            }
          },
          "categories": [
            "Activity"
          ]
        }
      ]
    }
  ]

在这种情况下,测试应该失败,因为第二个数组中的值为 20.01

标签: arrayspostman

解决方案


我不确定您从哪里复制了该代码,但它永远不会起作用,因为所有引用都与不同的响应主体相关。

为了保持相同的约定并throw new Error在那里你可以这样做:

pm.test('Value is not below 50', () => {
    _.each(pm.response.json().groups[0].items, (arrItem) => {
        if (arrItem.priceStartingAt.value < 50) {
            throw new Error(`Array contains ${arrItem.priceStartingAt.value}`)
        }
    })
});

或者你可以检查项目是否不在下面50这样。

pm.test('Value is not below 50', () => {
    _.each(pm.response.json().groups[0].items, (arrItem) => {
            pm.expect(arrItem.priceStartingAt.value).to.not.be.below(50)
    })
});

推荐阅读