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?
As already mentioned, the code in the task can't be causing the error
so it must be this code
which means you are not extracting the response correctly.
Try parsing
or else examine what the response is and adjust accordingly.
There isn't enough information to say exactly, because you jumped to the wrong conclusion. In fact, the error has nothing to do with the task!