Search code examples
node.jsmockingcypressfsstub

Override fs functions


I am doing some E2E tests using Cypress.

Since it doesnt support node functions such as those from fs, I have mocked them as below.

In my test file:

window.Cypress.fs = require('fs')
window.Cypress.fs.existsSync = () => { return true // custom return }
window.Cypress.fs.lstatSync = () => { // custom return }

But now I am getting some error:

fs.lstatSync(...).isFile is not a function

How can I override/mock/stub isFile()?

I tried doing:

window.Cypress.fs.lstatSync.isFile = () => { return true }
//and
window.Cypress.fs.lstatSync().isFile = () => { return true }

But it doesn't work.

Here is my source code (not the mock):

return fs.lstatSync(filePath).isFile()

Any thoughts??


Solution

  • Since you execute lstatSync() and then use its results, you need to write:

    window.Cypress.fs.lstatSync = () => { 
      return { 
        isFile() { return true }
      }
    }