How to convert csv into JSON in cypress

Viewed 3009

Installed convert-csv-to-jsonnpm package

Used below line in my code:

csvToJson.generateJsonFileFromCsv(fileInputName,fileOutputName);

giving me an error saying

fs.readFileSync is not a function

Also installed fs npm package having version "fs": "0.0.1-security" but No Luck

1 Answers

You can read the csv file from spec file using:

cy.readFile('file.csv')
  .then((data) => {
     cy.task('csvToJson', data).then((data) => {
            //process data
        })
   })

After that you create a task in plugins/index.js

csvToJson (data) {
  var lines=data.split("\n");
  var result = [];
  var headers=lines[0].split(",");
  for(var i=1;i<lines.length;i++){

      var obj = {};
      var currentline=lines[i].split(",");

      for(var j=0;j<headers.length;j++){
          obj[headers[j]] = currentline[j];
      }
      result.push(obj);
  }
  // console.log(result)
  return result
}

This will will do the job

Related