Cypress调用cypress.config.js中createExcelFile任务参数异常问题
问题分析与解决
问题根源
Cypress 的 cy.task() API 仅支持传递两个参数:第一个是任务名称,第二个是单个参数值(可以是字符串、数字、对象等)。你当前调用时传入了4个参数,导致任务函数中只有第一个参数filePath能正确接收,headers和data都会被解析为undefined,从而触发后续的报错。
修复步骤
1. 修改 commands.js 中的任务调用
把需要传递的所有参数打包成一个对象,作为cy.task()的第二个参数:
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', { filePath: excelFilePath, headers: headers, data: extractedData }); localStorage.setItem('token', res.body.token); localStorage.setItem('refreshToken', res.body.refreshToken); }); }); });
2. 修改 cypress.config.js 中的任务定义
调整任务函数,接收这个对象并解构出需要的参数:
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 }); } });
验证逻辑
修改后,任务函数就能正确接收到headers和extractedData,不会再出现undefined的情况,Excel文件生成逻辑也能正常执行。
内容的提问来源于stack exchange,提问作者paul
相关产品推荐
相关产品推荐

