Raj*_*Kon 2 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);
});
});
Run Code Online (Sandbox Code Playgroud)
我首先验证了上面的代码:
>tsc temp.ts
>node temp.js
Run Code Online (Sandbox Code Playgroud)
正如我所说,它运行良好,但为什么相同的代码在 Cypress 中不起作用,但会出现以下错误:
类型错误:fs.readdir 不是函数
您不能在 cypress 中使用节点模块,因为 cypress 在浏览器中执行测试代码。要使用节点模块,您必须使用插件文件中定义的任务(在节点进程中执行)(很重要,因为插件文件是在节点上下文中执行的)。
所以你必须告诉 cypresscypress.json你正在使用插件文件:
{
...
"pluginsFile": "cypress/plugins/plugins.js",
...
}
Run Code Online (Sandbox Code Playgroud)
然后在 中定义一个任务plugins.js:
on('task', {
readdir({ path }) {
return fs.readdir(path, .....);
}
});
Run Code Online (Sandbox Code Playgroud)
使用这样的任务:
cy.task("readdir", { path: "..." }, { timeout: 30000 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5758 次 |
| 最近记录: |