tschaub / mock-fs

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

`fs.writeFileSync` with a relative path should treat paths as relative to `process.cwd()` #372

Closed jfdoming closed 1 year ago

jfdoming commented 1 year ago

Hi all, first of all, awesome library (thanks for it)! I was running into the bug I mentioned in the title and wanted to confirm this is not intended behaviour. Here's a minimal test case:

import fs from "fs";
import path from "path";

test("writeFileSync writes relative paths to process.cwd()", () => {
  fs.mkdirSync("test/");
  process.chdir("test/");
  fs.writeFileSync("file.txt", "");
  expect(fs.realpathSync("file.txt")).toBe(path.join(process.cwd(), "file.txt"));
});

At least on my local computer (Node v19.6.0, mock-fs v5.2.0), this test passes normally. However, if I enable mock-fs, the test fails like so:

import fs from "fs";
import path from "path";

// Added
import mock from "mock-fs";
beforeEach(() => mock());
afterEach(mock.restore);

test("writeFileSync writes relative paths to process.cwd()", () => {
  fs.mkdirSync("test/");
  process.chdir("test/");
  fs.writeFileSync("file.txt", "");
  expect(fs.realpathSync("file.txt")).toBe(path.join(process.cwd(), "file.txt"));
});
Expected: "/Users/user/project/test/file.txt"
Received: "/Users/user/project/file.txt"

Please let me know if there's a misunderstanding of what's supported by mock-fs here! I didn't see any mention of relative paths not being supported (or only absolute paths being supported) here in the README, so I figured it would be good to bring up.

3cp commented 1 year ago

For me to debug, may I know what test tool (jest?) are you using?

jfdoming commented 1 year ago

For me to debug, may I know what test tool (jest?) are you using?

Yep, this is Jest. Interesting, I thought this wasn't related to the specific framework, but I just tested this in a node shell and it seems to work fine...

3cp commented 1 year ago

Jest is patching nodejs internal too. So there are quite few known issues when working with mock-fs.

You can try switch to other test tool if it's easy to switch and if you definitely wanted mock-fs.

The other option is to use jest with real file system. In linux, you can mount a memfs/tmpfs in RAM for testing.

jfdoming commented 1 year ago

I see. I think I can work around changing directories in this way, fortunately. I'll close the issue, but feel free to reopen it if you feel like this needs to be fixed.