【问题标题】:Test if Postman response body Json is an array or object测试 Postman 响应体 Json 是数组还是对象
【发布时间】:2019-05-18 18:19:54
【问题描述】:

我有一个正在测试的 API,我希望 responseBody 是一个 Json 对象(以“{”开头)。然而,由于意外事件,响应可能会以数组形式返回(以“[”开头)。

如何使用 Postman 测试确定 responseBody 的类型(数组或对象)?

到目前为止,我拥有的最好的是: 当期望一个对象(不是数组)时

var bodyJson = pm.response.json();
tests["Response should not be an array"] = !(bodyJson instanceof Array);

【问题讨论】:

  • 在某些使用 API 响应的情况下,它可能会将 JSON 对象单独放入一个数组中。
  • 您可以使用不同的工具来检查它,例如带有响应断言的 JMeter

标签: javascript postman


【解决方案1】:

你可以使用:

pm.test('is an Array', () => pm.expect(pm.response.json()).to.be.an('array').but.not.an('object'))

取自 ChaiJS - 它内置于原生 Postman 应用程序中。

【讨论】:

    【解决方案2】:

    例如你有以下 json

    {
      "testA": [1, 2],
      "testB": {"a": "b"}
    }
    

    你可以使用Array.isArray()

    var bodyJson = pm.response.json();
    tests["Response should not be an array"] = !Array.isArray(bodyJson['testA']); // false
    //tests["Response should not be an array"] = !Array.isArray(bodyJson['testB']);  // true
    

    或者

    var bodyJson = pm.response.json();
    pm.test("is Array Test", function() {
        var notArray = !Array.isArray(bodyJson.testA) // false
        // var notArray = !Array.isArray(bodyJson.testB) // true
        pm.expect(notArray).to.eql(true);;
    });
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2021-06-22
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      相关资源
      最近更新 更多