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 is not a function

1

2 Answers

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).

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

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

Then define a task in plugins.js:

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

Use the task like this:

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

Surprisingly both the statements below work well in Windows machine to get the directory (Note that this solution is a workaround due to the fact that Cypress tests run in browser environment.)

 cy.exec('pwd').then((result) => cy.log('pwd res:' + JSON.stringify(result)) ); cy.exec('cd').then( (result) => cy.log('cd res:' + JSON.stringify(result)) ); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy