【问题标题】:Cannot read properties of undefined looping through XLSX file in Cypress test在赛普拉斯测试中无法通过 XLSX 文件读取未定义循环的属性
【发布时间】:2021-12-01 20:19:48
【问题描述】:

我正在尝试在赛普拉斯测试中将 XLSX 文件中的值转换为 JSON 文件。

我已经完全复制了this blog 的代码,但是当我点击以下行时:

console.log(jsonData[index].data)

我收到此错误消息:

无法读取未定义的属性(读取“1”)

这是我的spec.js 文件中的代码:

describe('convert data to Json', () => {
    it('read data from xcel', () => {
        cy.parseXlsx('cypress/fixtures/excelData.xlsx').then((jsonData) => {
            const rowLength = Cypress.$(jsonData[0].data).length
            for (let index = 0; index < rowLength; index++) {
                var jsonData = jsonData[index].data
                console.log(jsonData[index].data)
                cy.writeFile("cypress/fixtures/xlsxData.json", { username: jsonData[0][0], password: jsonData[0][1] })
            }
        })
    })
})

这里是我的 parseXlsx 函数定义的地方:

插件/index.js

const xlsx = require('node-xlsx').default;
const fs = require('fs'); // for file
const path = require('path'); // for file path

module.exports = (on, config) => {
  on('task', {
    parseXlsx({ filePath }) {
      return new Promise((resolve, reject) => {
        try {
          const jsonData = xlsx.parse(fs.readFileSync(filePath));
          resolve(jsonData);
        } catch (e) {
          reject(e);
        }
      });
    }
  });
}

我的cypress/fixtures/excelData.xlsx 文件如下所示:

用户名密码

用户名1 密码1

用户名2密码2

谁能告诉我如何解决这个错误?

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    我设法找到了解决方案:

    describe('convert data to Json', () => {
        it('read data from xcel', () => {
            cy.parseXlsx('cypress/fixtures/excelData.xlsx').then((jsonData) => {
                const rowLength = Cypress.$(jsonData[0].data).length
    
                for (let i = 0; i < rowLength; i++) {
                    cy.log('Username: ' + jsonData[0].data[i][0]);
                    cy.log('Password: ' + jsonData[0].data[i][1]);
                    cy.writeFile("cypress/fixtures/xlsxData.json", { usernameValue: jsonData[0].data[i][0], passwordValue: jsonData[0].data[i][1] })
                }
            })
        })
    })  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多