0

A function I created in commands.js does not work in cucumber step definitions. Yet, another function with a simple return works in the same step definition.

Commands.js

Cypress.Commands.add('excelData', async () => {

    const ExcelJs = require('exceljs')

    var columnArray = [];

    var workbook = new ExcelJs.Workbook()
    await workbook.xlsx.readFile('E:/Automations/Cypress/FrameworkToCucumberSpecFlow/cypress/downloads/exceldata.xlsx')
    var worksheet = workbook.getWorksheet('sampledatab')

    worksheet.eachRow((row) => {
        row.eachCell((cell) => {
            columnArray.push(cell.value)
        })
    })

    columnArray.splice(0, 1) 

    return cy.wrap(columnArray)

})

Cypress.Commands.add('TestCommandsJS', () => {
    return 'TestCommandsJS works'
})

step definition

When('I compare that list with the Excel specification sheet list', () => {

    cy.excelData().then(data => { //this does not work
        cy.log(data)
    })

    cy.TestCommandsJS().then(data => { //this work fine
        cy.log(data)
    })

})

Any help appreciated.

1 Answer 1

0

The exceljs library you are using is a Nodejs library.

You will have to move the custom command code to a task - see Cypress task docs.

on('task', {
  async excelData({path, sheet}) {
    const ExcelJs = require('exceljs')
    const columnArray = []
    const workbook = new ExcelJs.Workbook()
    await workbook.xlsx.readFile(path)
    const worksheet = workbook.getWorksheet(sheet)
    worksheet.eachRow(row => {
      row.eachCell(cell => {
        columnArray.push(cell.value)
      })
    })
    return columnArray
  }
})

Then your test will use it:

cy.task('excelData', {
    path: 'SampleData.xlsx',   // path relative to project root
    sheet: 'SalesOrders'       // specify the sheet in test not in task 
  })
  .then(data => data.slice(0,7))  // headers
  .should('deep.eq', 
    ['OrderDate', 'Region', 'Rep', 'Item', 'Units', 'Unit Cost', 'Total'])
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer/solution. Thanks Samuda. Very grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.