Reputation: 139
I have a scenario where i have to convert a csv file in to JSON object and use the data in script for performing data driven testing. If the file has multiple rows of data, then script should be executed for multiple iterations.
Csv File
name,description
CHOne,First Change
CHTwo,Second Change
Expected JSON format
{
"name":"CHOne",
"description":"First Change"
},
{
"name":"CHTwo",
"description":"Second Change"
}
Upvotes: 0
Views: 4119
Reputation: 8662
You can install a 3d party library to parse CSV
to JSON
easier and then use a simple for of
loop to run test with different objects.
npm i -D csvtojson
Parse from CSV file to JSON array and run test with different data:
const csvFilePath = '<replace it with the path to csv file>'
const csv = require('csvtojson');
csv()
.fromFile(csvFilePath)
.then(users => {
console.log(users) // will print
/**
* [
* {name:"CHOne", description: "First Change"},
* {name:"CHTwo", description: "Second Change"}
* ]
*/
// now you can run one test for each user's object
for (const { name } of users) {
test(`testing with ${name}`, async () => {
// ...
});
}
})
Upvotes: 2