【问题标题】:Why do I get error `TypeError: fs.readdir is not a function` in Cypress为什么我在 Cypress 中收到错误 `TypeError: fs.readdir is not a function`
【发布时间】:2019-11-23 18:23:54
【问题描述】:

我编写了这段代码,它使用 TypeScript 编写的很好。当我在赛普拉斯的测试文件中使用相同的代码时,我收到错误TypeError: fs.readdir is not a function

import * as fs from 'fs'

let inputPath: String = "C:\\Users\\rkon";
let replacementString = "/";
let newInputPath = inputPath.split('\\').join(replacementString)
console.log('path after replacement: ' + newInputPath);

fs.readdir(newInputPath as string, function (err: any, files: any[]) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {
        console.log('file: ' + file);
    });
});

我首先验证了上面的代码:

>tsc temp.ts
>node temp.js

正如我所说,它运行良好,但为什么相同的代码在 Cypress 中不起作用,并出现以下错误:

TypeError: fs.readdir 不是函数

【问题讨论】:

  • 看起来你可能需要修改你的模块分辨率标志。你在你的 node_modules 目录中也安装了 fs 吗?

标签: typescript cypress


【解决方案1】:

您不能在 cypress 中使用节点模块,因为 cypress 在浏览器中执行测试代码。 要使用节点模块,您必须使用插件文件中定义的任务(在节点进程中执行)(很重要,因为插件文件是在节点上下文中执行的)。

所以你必须在cypress.json 中告诉 cypress 你正在使用插件文件:

{
    ...
    "pluginsFile": "cypress/plugins/plugins.js",
    ...
  }

然后在plugins.js中定义一个任务:

on('task', {
    readdir({ path }) {
      return fs.readdir(path, .....);
    }
  });

像这样使用任务:

cy.task("readdir", { path: "..." }, { timeout: 30000 });

【讨论】:

    【解决方案2】:

    令人惊讶的是,以下两个语句在 Windows 机器上都可以很好地获取目录(请注意,由于赛普拉斯测试在浏览器环境中运行,因此此解决方案是一种解决方法。)

            cy.exec('pwd').then((result) =>
                cy.log('pwd res:' + JSON.stringify(result))
            );
    
            cy.exec('cd').then( (result) =>
                cy.log('cd res:' + JSON.stringify(result))
            );
    

    【讨论】:

      猜你喜欢
      • 2020-09-13
      • 2022-06-22
      • 1970-01-01
      • 2015-10-11
      • 2021-11-20
      • 2015-08-10
      • 2017-07-22
      • 1970-01-01
      • 2020-01-20
      相关资源
      最近更新 更多