我有一个基于JSON的测试数据,如何遍历此测试数据以针对每个cred对象运行测试?
cred: {
nameValue: 'ant',
emailValue: 'ant@gmail.com',
passwordValue: 'ant',
},
cred: {
nameValue: 'bat',
emailValue: 'bat@gmail.com',
passwordValue: 'bat',
},
答案 0 :(得分:0)
您的测试数据JSON文件应该是这样的
[
{
"nameValue": "ant",
"emailValue": "ant@gmail.com",
"passwordValue": "ant"
},
{
"nameValue": "bat",
"emailValue": "bat@gmail.com",
"passwordValue": "bat"
}
]
现在您可以按索引访问它们(如数组中一样)
const testDataObject = require("path to testData json");
// to loop on all elements
testDataObject.forEach(function(element) {
it(' test case def ', function() {
console.log("nameValue "+ element['nameValue']+ "emailValue
"+element['emailValue'] + "passwordValue "+element[passwordValue]);
});
});
// to select any particular index
it(' test case def ', function() {
console.log("nameValue "+ testDataObject[1]['nameValue']+ "emailValue
"+testDataObject[1]['emailValue'] + "passwordValue "+testDataObject[1][passwordValue]);
});
});
并将您的testData文件名命名为Credentials_Valid.json(最佳做法)
或 您可以通过这种方式完成
{
"cred1":
{
"nameValue": "ant",
"emailValue": "ant@gmail.com",
"passwordValue": "ant",
},
"cred2":
{
"nameValue": "bat",
"emailValue": "bat@gmail.com",
"passwordValue": "bat",
}
}
并通过以下方式访问nodejs代码中的测试数据:
console.log( `${testDataObject['cred1']["nameValue"]}` );
console.log( `${testDataObject['cred1']["emailValue"]}` );
console.log( `${testDataObject['cred1']["passwordValue"]}` );