【问题标题】:How to remove "_fs.readFileSync is not a function" error from cypress test如何从 cypress 测试中删除“_fs.readFileSync 不是函数”错误
【发布时间】:2020-09-08 16:07:08
【问题描述】:

我想从我的 excel 表的特定单元格中读取数据,然后在我的 cypress 测试中使用该数据。文件名为“qaautomation.xlsx”,工作表名称为“Input”,我想从单元格 B2 中读取数据。我编写了以下代码来访问该值

 /// <reference types ="cypress" />
var xlsx = require ("xlsx");
var workbook= xlsx.readFile("qaautomation.xlsx");
var worksheet= workbook.Sheets["Input"];
var cellB2value= 'B2';
var cellB2=worksheet[cellB2value];
var cellB2_value=(cellB2.v);

下面编写的代码是使用该值的地方。

        describe('Typing the address', function(){
    
    it ('should open the link', function(){
        cy.visit(cellB2_value) //here comes the value from cell B2
})})

当我运行上面的代码时,我得到以下错误

The following error originated from your test code, not from Cypress.

  > _fs.readFileSync is not a function

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

Check your console for the stack trace or click this message to see where it originated from.

有什么办法可以消除这个错误吗?

【问题讨论】:

标签: javascript node.js cypress xlsx readfile


【解决方案1】:

这是 XLSX 读取功能如何处理 webpack 和浏览器的安全功能不直接访问文件系统的问题。

您需要通过 ajax 调用读取文件,然后以这种方式将其“读取”到 xlsx。这里有一个演示:

https://github.com/SheetJS/sheetjs/tree/master/demos/xhr

fetch(url).then(function(res) {
  /* get the data as a Blob */
  if(!res.ok) throw new Error("fetch failed");
  return res.arrayBuffer();
}).then(function(ab) {
  /* parse the data when it is received */
  var data = new Uint8Array(ab);
  var workbook = XLSX.read(data, {type:"array"});

  /* DO SOMETHING WITH workbook HERE */
});

【讨论】:

  • 我已经尝试了上述解决方案,但现在它给了我“无法读取未定义的属性 'B2'”错误
  • 好像没有打开文件 路径是否正确?在您的示例中,该文件需要与查找它的代码位于同一文件夹中
  • 我的测试文件“browser.spec.js”和“qaautomation.xlsx”文件都在cypress文件夹内的集成文件夹中。
  • 看起来“读取”功能只支持文件流。 github.com/SheetJS/sheetjs#parsing-workbooks能不能先从ajax调用中加载数据,然后传给read方法?
  • 我的文件夹中有 xlsx 文件,不需要下载。由于我对 ajax 调用一无所知,您能否澄清为什么我必须通过 ajax 调用读取 xlsx 文件?我正在节点环境中读取文件,测试在柏树中。基本上我需要知道如何从 cypress 测试中运行节点代码。
【解决方案2】:

嗯.. 如果您使用的是(相对)较新版本的 cypress,则有专门的 API:https://docs.cypress.io/api/commands/writefile#Examples

来自文档:

cy.writeFile('path/to/message.txt', 'Hello World')
cy.readFile('path/to/message.txt').then((text) => {
  expect(text).to.equal('Hello World') // true
})

耶!

【讨论】:

    【解决方案3】:

    将导致该问题的功能移至cypress/support/,例如commands.js

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2021-03-10
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2020-01-05
      • 2019-11-28
      相关资源
      最近更新 更多