arrays - 在 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) ]
解决方案
通过使用_.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)
});
推荐阅读
- ruby-on-rails - 不同模型列之间的条件
- scroll - 为什么我的超链接不能滚动到 Edge 中的相应位置?
- javascript - React testing-library - 测试在第一个 useEffect 挂钩中设置状态的 Promise
- python - 使用 Scrapy Spider 使用 JavaScript 表单登录网站
- c - 如何将参数传递给 C 中的 pthread 线程函数?
- android - 如何在颤动中显示倒数计时器和警报框
- google-sheets - 谷歌表格脚本自动将所有表格的列表添加(和更新)到一个范围内?
- java - ebay OAuth 2.0 库无法解决方法初始化()
- c - linux命令的C实现
- node.js - 使用 Mocha、Chai、node.js 测试异步方法