我需要验证接下来的两个密钥: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,控制台会正确地向我显示2个参数。
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')
})
}
})
})