为什么在赛普拉斯中出现错误`TypeError:fs.​​readdir不是函数` [英] Why do I get error `TypeError: fs.readdir is not a function` in Cypress

查看:95
本文介绍了为什么在赛普拉斯中出现错误`TypeError:fs.​​readdir不是函数`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码,用TypeScript编写的代码工作正常.当我在cypress的测试文件中使用相同的代码时,出现错误 TypeError:fs.​​readdir不是函数

I wrote this code and it works fine that is written in TypeScript. When I use the same code in the test file in cypress I get error 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);
    });
});

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

I verified the above code by first doing:

>tsc temp.ts
>node temp.js

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

As I said it worked fine but why does the same code not work in Cypress giving the following error:

TypeError:fs.​​readdir不是函数

TypeError: fs.readdir is not a function

推荐答案

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

you can not use node modules within cypress because cypress executes test code in the browser. To use node modules, you must use tasks (which are executed in the node process) that are defined in the plugins file (important, because the plugins file is executed in the node context).

因此,您必须在 cypress.json 中告诉cypress您正在使用插件文件:

So you have to tell cypress in the cypress.json that you are using a plugins file:

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

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

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

使用这样的任务:

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

这篇关于为什么在赛普拉斯中出现错误`TypeError:fs.​​readdir不是函数`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆