tschaub / mock-fs

Configurable mock for the fs module
https://npmjs.org/package/mock-fs
Other
906 stars 86 forks source link

Test fails when using mock-fs #351

Open YonatanKra opened 2 years ago

YonatanKra commented 2 years ago

In my tests I've just required mock-fs and then used:

mock({
'file.ts': fileContents,
});

I get an error:

node:fs:2486
      handleErrorFromBinding(ctx);
      ^

Error: ENOENT: no such file or directory, lstat '/Users/ykra/projects/open-source/playwright-watch/node_modules/exit'
    at Object.realpathSync (node:fs:2486:7)
    at toRealPath (node:internal/modules/cjs/loader:394:13)
    at tryFile (node:internal/modules/cjs/loader:390:10)
    at tryExtensions (node:internal/modules/cjs/loader:402:22)
    at tryPackage (node:internal/modules/cjs/loader:347:5)
    at Function.Module._findPath (node:internal/modules/cjs/loader:566:18)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18) {
  syscall: 'lstat',
  code: 'ENOENT',
  errno: -2,
  path: '/Users/ykra/projects/open-source/playwright-watch/node_modules/exit'
}

If I remove the mock function call, the tests run (without the mock of course). Any idea why this might happen?

regseb commented 2 years ago

mock-fs replaces the entire file system, so there is virtually only one file on your computer: file.ts. Your program (or one of its dependencies) is trying to open the exit file which doesn't exist. You have to add the exit file in the mock:

mock({
    'file.ts': fileContents,
    'node_modules/exit': mock.load('node_modules/exit'),
});
3cp commented 2 years ago

Because mockfs is designed to monkey patch fs subsystem, normally it can only survive small scale unit test. Mock fs, test something, then restore fs.

It doesn't play well with other bigger tools which deals with file system constantly. For example jest. It will be very surprising if mockfs can work with playwright nicely.

mitsuru793 commented 1 year ago

I have same issue. I have resolve by mock.load.

mock({
    'node_modules/exit': mock.load('node_modules/exit'),
});

But, I use restore function then I needn't use load.

const mock = require('mock-fs')

afterEach(() => {
  mock.restore()
})

it('should be successful.', async () => {
  mock()
})

It's written on README. Please search by 'test' or 'restore'.


This issue can be closed.