[英]POSTMAN : parsing a JSON response, how deep can I go into the response?
[英]Postman: How can validate a key in JSON response
我需要验证接下来的 2 个键: key1
和key2
:
{
"data": [
{
"id": "123",
"type": "something",
"created": "1540952074",
"test": [
{
"key1": "asd123",
"key2": "166802"
}
]
},
我只对验证这些密钥是否已经存在感兴趣。
我做了这个测试:
pm.test('returns the correct parameters by type', () => {
for (i = 0; i < jsonData.data.length; i++) {
if (jsonData.data[i].type === 'something') {
// for (j = 0; j < jsonData.data.test.length; j++) {
pm.expect(jsonData.data[i]).to.have.property('id');
pm.expect(jsonData.data[i]).to.have.property('type');
pm.expect(jsonData.data[i]).to.have.property('created');
pm.expect(jsonData.data[i].test[0]).to.have.property('key1');
pm.expect(jsonData.data[i].test[0]).to.have.property('key2');
}
}
});
返回以下错误:
returns the correct parameters by type | TypeError: Cannot read property '0' of undefined
但是如果我把一个带有jsonData.data[i].test[0]
的 console.log ,控制台会正确地向我显示两个参数到一个对象中:
Object:{}
key1:"asd123"
key2:"166802"
知道我该怎么做吗?
谢谢
我真的看不到完整的响应数据,但这可能对你有用:
let jsonData = {
"data": [
{
"id": "123",
"type": "something",
"created": "1540952074",
"test": [
{
"key1": "asd123",
"key2": "166802"
}
]
}
]
}
pm.test("My Test", () => {
_.each(jsonData.data, (item) => {
if(item.type === "something") {
pm.expect(_.first(item.test)).to.have.keys('key1', 'key2')
}
})
})
由于这只是使用来自其jsonData
对象的数据的测试示例,因此这不适用于您的响应数据。
你可以试试这个吗?
pm.test("My Test", () => {
_.each(pm.response.json().data, (data) => {
if(data.type === "something") {
_.each(data.test, (test) => {
pm.expect(test).to.have.keys('key1', 'key2')
})
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.