我写了这段代码,它用 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/