我在邮递员中有一个测试,我可以在数组中验证字符串值,但前提是我知道返回它的索引。我遇到的问题是返回值的索引可以是随机的。
这就是json看起来我正在验证的内容。
{
"cart": [{
"offeringId": "1234",
"offeringName": "Test1",
"totalOfferingAmount": -15,
"offeringTypeQualifier": "Test",
"productTypeQualifier": "Product",
"quantity": -1,
"messages": [],
"autoAdd": false,
"autoAction": "removed",
"addedByProcessor": true,
"qualificationLevel": "FQ",
"qualificationDetails": []
}, {
"offeringId": "5678",
"offeringName": "Test2",
"totalOfferingAmount": -15,
"offeringTypeQualifier": "Test",
"productTypeQualifier": "Product",
"quantity": -1,
"messages": [],
"autoAdd": false,
"autoAction": "removed",
"addedByProcessor": true,
"qualificationLevel": "FQ",
"qualificationDetails": []
}],
"isCartValidForCheckout": true,
"_status": []
}
这是我的邮差测试
var data = JSON.parse(responseBody);
tests ["Verify offeringId"] = data.cart[0].offeringId === "1234"
答案 0 :(得分:1)
在Postman中,一个很好的速记,带有用于测试已知值的正则表达式。
cart.forEach(function(x, i) {
tests['Test known offeringName ' + cart[i].offeringName ] = true === /^Test1$|^Test2$/.test(cart[i].offeringName); }
)
答案 1 :(得分:1)
这是在当前版本的Postman v6.1.2(本机应用程序,而不是浏览器)中测试的答案:
pm.test("Test for offeringId=1234", function () {
var jsonData= JSON.parse('{"cart":[{"offeringId":"1234","offeringName":"Test1","totalOfferingAmount":-15,"offeringTypeQualifier":"Test","productTypeQualifier":"Product","quantity":-1,"messages":[],"autoAdd":false,"autoAction":"removed","addedByProcessor":true,"qualificationLevel":"FQ","qualificationDetails":[]},{"offeringId":"5678","offeringName":"Test2","totalOfferingAmount":-15,"offeringTypeQualifier":"Test","productTypeQualifier":"Product","quantity":-1,"messages":[],"autoAdd":false,"autoAction":"removed","addedByProcessor":true,"qualificationLevel":"FQ","qualificationDetails":[]}],"isCartValidForCheckout":true,"_status":[]}');
//var jsonData = pm.response.json(); // This is the production response. Uncomment this.
var size = jsonData.cart.length; // cart object is array. Get its size.
var flag = false;
console.log("Test for offeringId. size=[" + size + "]");
for(var i = 0; i < size; i++) {
console.log("jsonData.cart[" + i + "].offeringId=[" + jsonData.cart[i].offeringId + "]"); // Debug
console.log(jsonData.cart[i].offeringId);
if (jsonData.cart[i].offeringId == "1234") {
console.log("1234 is found........");
flag = true;
}
}
pm.expect(flag).to.eql(true);
});
答案 2 :(得分:0)
我认为你应该遍历整个数组并检查字符串值是否包含在任何索引中。
var array = JSON.parse(responseBody)
let testResult = array.find((each)=>{
return each.offeringID === '1234'
});
答案 3 :(得分:0)
一旦验证成立,我不知道你打算做什么,但如果只是为了检查特定的id是否在响应中,你可以随时做
var size = data.cart.length;
var flag = false;
for(var i = 0; i < size; i++) {
if(data.cart[i].offeringId === "1234") {
flag = true;
}
}