首页 > 解决方案 > 在 Postman 中验证对象数组

问题描述

我对 Postman 很陌生,并不是一个特别好的程序员。我正在测试一个 API 并尝试验证其中包含一个数组的响应的一部分,如下所示:

"processors": [
        {
            "name": "ARTPEC-5",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        },
        {
            "name": "SSL",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        },
        {
            "name": "ARTPEC-7",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        }
    ]

现在,我想验证数组是否带有上述对象。它们可能在数组中以任何顺序出现,所以我不能使用像 jsonData.processors[0] 这样的索引来引用对象,然后像这样一一验证它们。我需要一个通用的验证方法。我试过这个没有用:

pm.test("Check if the response has processors", function () {
     pm.expect(jsonData.processors).to.have.members([
  {
            "name": "ARTPEC-5",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        },
        {
            "name": "SSL",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        },
        {
            "name": "ARTPEC-7",
            "type": "SOC",
            "url": null,
            "releaseNotes": null,
            "cdnUrl": null,
            "cdnReleaseNotes": null
        }]);
});

这种方法只会给我一个神秘的错误消息 AssertionError: expected [ Array(3) ] to have the same members as [ Array(3) ]

标签: arraysvalidationpostman

解决方案


通过使用_.differenceWith(),如果数组对象及其属性没有差异,您将获得空数组。你可以断言为 -

var _ = require('lodash')

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 1, 'y': 2 }];

var arr = _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);

console.log(arr);
console.log(objects.length);

// assert that difference should be empty

pm.test("array difference", function () {
    pm.expect([]).to.eql(arr)
});

推荐阅读