0

Suppose that you have a JSON file that contains data like this:

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

How to read it using cypress and print the name one by one using cypress?

Alapan Das
  • 17,144
  • 3
  • 29
  • 52

2 Answers2

1

You can do something like this:

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

Test Runner Screenshot:

Test runner screenshot

If you want to read from a JSON file which is present somewhere in your repo you can:

//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)
  }
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • Thanks for your reply. This data should be read from a JSON file as this data is initially i got it dynamically from a previous step and i save it in this file – Mohammad Osama Nov 16 '21 at 09:28
  • So this file is saved as a `.json` file somewhere in your repo and you want to read it from there ? I have updated my answer. – Alapan Das Nov 16 '21 at 09:34
0

If this is your test data, you can iterate over the array and dynamically create a test case for each object in the array:

[
  {
      "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);
  });
});

And the result from test runner:

enter image description here

Just beware that you left out one bracket, so your data is not a valid JSON.

pavelsaman
  • 7,399
  • 1
  • 14
  • 32