【问题标题】:How loop and read JSON data in cypress如何在 cypress 中循环和读取 JSON 数据
【发布时间】:2021-12-27 08:37:17
【问题描述】:

假设您有一个 JSON 文件,其中包含如下数据:

[
  {
    name: 'Data Groups',
  },
  {
    name: 'Transaction start Filter',
  },
  {
    name: 'Filter',
  },
  {
    name: 'Graph, Tables',
  },
  {
    name: 'Trending with filters',
  },
  {
    name: 'Graph, area & Pie',
  },
]

如何使用cypress读取并使用cypress一一打印出名称

【问题讨论】:

    标签: cypress cypress-component-test-runner cypress-testing-library


    【解决方案1】:

    你可以这样做:

    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)
      }
    })
    

    【讨论】:

    • 感谢您的回复。此数据应从 JSON 文件中读取,因为此数据最初是我从上一步动态获取的,并将其保存在此文件中
    • 所以这个文件被保存为.json 文件在你的仓库中的某个地方,你想从那里读取它吗?我已经更新了我的答案。
    【解决方案2】:

    如果这是您的测试数据,您可以遍历数组并为数组中的每个对象动态创建一个测试用例:

    [
      {
          "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。

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多