tschaub / mock-fs

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

Create Mock without replacing the original module #324

Open gsuess opened 3 years ago

gsuess commented 3 years ago

I usually like to pass all environment bound interfaces as a parameter, including fs.

Here is a simple Example:

import * as fs from "fs";
function  doSomething(something, fsEnv = fs) {
  // Do something with fsEnv
}

With this practice there is no necessity to temporarily disable an interface globally, which can cause some very unexpected issues (one of such issues is seen on the Readme with Jest Snapshots).

Is there a possibility to create a fs mock without actually messing with the origina fs?

With the example above, I would like to implement tests like this:

const fs = mockFs(fileTree);
doSomething(something, fs);

Without needing to call restore on anything.

gsuess commented 3 years ago

After looking into the source-code, it doesn't seem to be possible currently.

With a bit of refactoring however, this feature could be integrated though, by adding a doNotPatch option and return a mocked fs map that implements all interfaces that fs exports.

timofei-iatsenko commented 1 year ago

You can use https://www.npmjs.com/package/memfs or https://www.npmjs.com/package/memory-fs for this purpose