为什么在赛普拉斯中出现错误`TypeError:fs.​​readdir不是函数`

时间:2019-11-23 18:23:54

标签: 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[]) {
    let data_source_url_array = [];
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {
        console.log('f: ' + file);

    });
});

我首先通过以下方法验证了上述代码:

>tsc temp.ts
>node temp.js

正如我所说的那样,它工作正常,但是为什么相同的代码在赛普拉斯中不起作用,并给出以下错误:

  

TypeError:fs.​​readdir不是函数

2 个答案:

答案 0 :(得分: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 });

答案 1 :(得分:0)

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