Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read excel files in Cypress

Tags:

cypress

I am new to Cypress. How to read data from excel files using Cypress? Searched in google but could not find useful answers.

like image 278
Chaitanya K Avatar asked Nov 30 '25 02:11

Chaitanya K


1 Answers

In cypress you can create cypress task to read xlsx file with SheetJS library.

Usage

cypress\integration\read-xlsx.spec.js

context('Xlsx file', () => {
  it('Read excel file', () => {
    cy.task('readXlsx', { file: 'my-excel.xlsx', sheet: "Sheet1" }).then((rows) => {
      expect(rows.length).to.equal(543)
      // expect(rows[0]["column name"]).to.equal(11060)
    })
  })
})

Need to install xlsx

 $ npm install xlsx

Create read excel fuction

cypress\plugins\read-xlsx.js

const fs = require('fs');
const XLSX = require('xlsx');

const read = ({file, sheet}) => {
   const buf = fs.readFileSync(file);
   const workbook = XLSX.read(buf, { type: 'buffer' });
   const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
   return rows
}

module.exports = {
   read,
}

Use function as Cypress task (plugin)

cypress\plugins\index.js

const readXlsx = require('./read-xlsx')

module.exports = (on, config) => {
  on('task', {
    'readXlsx': readXlsx.read
  })
}
like image 112
Nebojsa Jevdjovic Avatar answered Dec 05 '25 16:12

Nebojsa Jevdjovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!