typescript - 为什么我在 Cypress 中收到错误 `TypeError: fs.readdir is not a function`

标签 typescript cypress

我写了这段代码,它用 TypeScript 写的很好。当我在 cypress 的测试文件中使用相同的代码时,我收到错误 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 is not a function

最佳答案

您不能在 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 });

关于typescript - 为什么我在 Cypress 中收到错误 `TypeError: fs.readdir is not a function`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010818/

相关文章:

Cypress .io : Waiting for results of exec command

continuous-integration - 如何重试失败的测试?

cypress - 文本字段 cypress 中的金额计算

typescript - 如何根据提供给第一个函数的参数推断参数?

typescript - 来自 API 错误的数据 [无法解析 UserService : (? 的所有参数]。

typescript - 在 TypeScript 中使用静态字符串作为 AngularJS 常量

testing - 如何获取 cypress 中特定属性值的数组

reactjs - 需要了解配置 React 和 cypress 的最佳方法

javascript - 在 typescript 中将字符串转换为数字而不丢失前导零,而不使用数组解决方案

javascript - 如何在 JSX/TSX 中使用 TypeScript 的转译函数