I have a task like this in cypress.config.js
async function setupNodeEvents(on, config) {
allureWriter(on, config);
await preprocessor.addCucumberPreprocessorPlugin(on, config);
on('task', { downloadFile });
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin.default(config)],
})
);
on("file:preprocessor", browserify.default(config));
on('task', {
log(message) {
console.log(message)
return null
}
});
on('task', {
createExcelFile(filePath, headers, data) {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet 1');
if (headers && Array.isArray(headers)) {
worksheet.addRow(headers);
console.log('Header Row:', headers);
}
// Add data rows if data is provided
if (data && Array.isArray(data)) {
data.forEach(row => {
worksheet.addRow(row);
console.log('Data Row:', row);
});
}
// Save the workbook to the specified file path
return workbook.xlsx.writeFile(filePath)
.then(() => {
return null; // Indicate that the task was handled
})
.catch(error => {
throw error; // Propagate the error if encountered
});
}
});
return config;
}
module.exports = defineConfig({
reporterOptions: {
charts: true,
reportPageTitle: "custom-title",
embeddedScreenshots: true,
inlineAssets: true,
saveAllAttempts: false,
},
e2e: {
setupNodeEvents,
----
}
}
}
});
And I am calling this createExcelFile
like this
Cypress.Commands.add('createImportDemoExcel', () => {
cy.fixture('testData/api/demo-api').then(call => {
cy.request('GET', callPath
).then(function (res) {
const apiResponse = res.body.data;
const extractedData = [];
apiResponse.forEach(item => {
const age = item.id;
const name = item.name;
const zip = item.yearLevelId;
extractedData.push([name, age, zip]);
});
const excelFilePath = "cypress/fixtures/testData/ImportData.xlsx";
let headers = ['Age', 'Name', 'Zip'];
cy.task('createExcelFile', excelFilePath, headers, extractedData);
localStorage.setItem('token', res.body.token);
localStorage.setItem('refreshToken', res.body.refreshToken);
});
});
});
But it is giving error as Header Row: undefined
and Cannot read properties of undefined (reading 'forEach')
. However the extractedData.push([name, age, zip]);
is generated fine.
Also if I cy.request
from config file within createExcelFile
then there is no error but if I call it from commands.js then it gives undefined
error for extractedData
and headers
What wrong am I doing?