Home > front end >  How to loop through rows of data in .CSV file in Cypress test?
How to loop through rows of data in .CSV file in Cypress test?

Time:10-27

In my Cypress test, I am trying to read data from a CSV file & loop through each row.

Below is the contents of my fixtures/logins.csv file:

enter image description here

I want to loop through each row of data to log into an application.

Here is my latest code, it just logs the CSV file data as a string currently:

const csvUploaded = 'cypress/fixtures/logins.csv'

it('CSV test', () => {
    cy.readFile(csvUploaded, 'utf-8').then((txt) => {
        cy.log(txt)
        cy.log(typeof txt)
    });
});

txt is the below string at the moment:

username,password john,pword1 james,myPassword frank,newPassword

CodePudding user response:

With the data in that format, you have to

  • split the single string txt by newline
  • split each line by |
  • remove empty values -trim strings of surrounding whitespace
cy.fixture('logins.csv')
  .then(txt => txt.split('\n').map(row => row.trim()))  // string to array of rows
  .then(rows => {
     const data = rows.slice(1)                         // remove headers
       .map(row => row.split('|')                       // split each row
         .filter(Boolean)                               // ignore start and end "|"
         .map(col => col.trim())                        // remove whitespace
       )
       .filter(row => row.length)                       // remove empty rows
     return data
})
.should('deep.eq', [
  ['john', 'pword1'], 
  ['james', 'myPassword'], 
  ['frank', 'newPassword']
])
.each(row => {
  console.log(row)
})

Markdown tables

Technically, that file is not CSV it's a markdown table (or can be treated as such).

This package Parse Markdown Table can help you parse it

it('parses a markdown table from fixture', async () => {
  
  const { createMarkdownArrayTable } = await import('parse-markdown-table')

  cy.fixture('logins.csv').then(txt => {
    createMarkdownArrayTable(txt).then(async table => {
      console.info('headers', table.headers)
      for await (const row of table.rows) {
        console.info('row', row)
      }
    })
  })
})
  • Related