如何在赛普拉斯中循环和读取 JSON 数据
How loop and read JSON data in cypress
假设您有一个 JSON 文件,其中包含如下数据:
[
{
name: 'Data Groups',
},
{
name: 'Transaction start Filter',
},
{
name: 'Filter',
},
{
name: 'Graph, Tables',
},
{
name: 'Trending with filters',
},
{
name: 'Graph, area & Pie',
},
]
如何使用 cypress 读取它并使用 cypress 一一打印 name?
你可以这样做:
var arr = [
{
name: 'Data Groups',
},
{
name: 'Transaction start Filter',
},
{
name: 'Filter',
},
{
name: 'Graph, Tables',
},
{
name: 'Trending with filters',
},
{
name: 'Graph, area & Pie',
},
]
for (var index in arr) {
cy.log(arr[index].name)
}
测试运行器截图:
如果您想读取存储库中某处的 JSON 文件,您可以:
//If the file is in fixtures folder
cy.fixture('data.json').then((data) => {
for (var index in data) {
cy.log(data[index].name)
}
})
//If the file is somewhere else in repo
cy.fixture('path to file/data.json').then((data) => {
for (var index in data) {
cy.log(data[index].name)
}
})
如果这是您的测试数据,您可以遍历数组并为数组中的每个对象动态创建一个测试用例:
[
{
"name": "Data Groups"
},
{
"name": "Transaction start Filter",
},
{
"name": "Filter",
},
{
"name": "Graph, Tables",
},
{
"name": "Trending with filters",
},
{
"name": "Graph, area & Pie",
}
].forEach(data => {
it(`Test ${JSON.stringify(data)}`, () => {
cy
.log(data.name);
});
});
测试运行器的结果:
请注意您遗漏了一个括号,因此您的数据无效 JSON。
假设您有一个 JSON 文件,其中包含如下数据:
[
{
name: 'Data Groups',
},
{
name: 'Transaction start Filter',
},
{
name: 'Filter',
},
{
name: 'Graph, Tables',
},
{
name: 'Trending with filters',
},
{
name: 'Graph, area & Pie',
},
]
如何使用 cypress 读取它并使用 cypress 一一打印 name?
你可以这样做:
var arr = [
{
name: 'Data Groups',
},
{
name: 'Transaction start Filter',
},
{
name: 'Filter',
},
{
name: 'Graph, Tables',
},
{
name: 'Trending with filters',
},
{
name: 'Graph, area & Pie',
},
]
for (var index in arr) {
cy.log(arr[index].name)
}
测试运行器截图:
如果您想读取存储库中某处的 JSON 文件,您可以:
//If the file is in fixtures folder
cy.fixture('data.json').then((data) => {
for (var index in data) {
cy.log(data[index].name)
}
})
//If the file is somewhere else in repo
cy.fixture('path to file/data.json').then((data) => {
for (var index in data) {
cy.log(data[index].name)
}
})
如果这是您的测试数据,您可以遍历数组并为数组中的每个对象动态创建一个测试用例:
[
{
"name": "Data Groups"
},
{
"name": "Transaction start Filter",
},
{
"name": "Filter",
},
{
"name": "Graph, Tables",
},
{
"name": "Trending with filters",
},
{
"name": "Graph, area & Pie",
}
].forEach(data => {
it(`Test ${JSON.stringify(data)}`, () => {
cy
.log(data.name);
});
});
测试运行器的结果:
请注意您遗漏了一个括号,因此您的数据无效 JSON。