{"name":"mock-fs","version":"5.4.1","keywords":["mock","fs","test","fixtures","file system","memory"],"author":{"url":"http://tschaub.net/","name":"Tim Schaub"},"license":"MIT","_id":"mock-fs@5.4.1","maintainers":[{"name":"tschaub","email":"tim.schaub@gmail.com"}],"homepage":"https://github.com/tschaub/mock-fs","bugs":{"url":"https://github.com/tschaub/mock-fs/issues"},"dist":{"shasum":"b00abc658cb19dbbf282fde2f05bb751cd1e12a5","tarball":"http://registry-npm.ywwl.com/mock-fs/download/mock-fs-5.4.1.tgz","fileCount":15,"integrity":"sha512-sz/Q8K1gXXXHR+qr0GZg2ysxCRr323kuN10O7CtQjraJsFDJ4SJ+0I5MzALz7aRp9lHk8Cc/YdsT95h9Ka1aFw==","signatures":[{"sig":"MEQCIBcYcdEMnNHTGAxSEcsrMPBPa7GbzLWe0/t9edfhlHR6AiAiteP+VSTN3uOpQE9f/DeFV2pCOeEuUfb6k4quhHxyoA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":107660,"size":23192,"noattachment":false,"key":"/mock-fs/-/mock-fs-5.4.1.tgz"},"main":"lib/index.js","engines":{"node":">=12.0.0"},"gitHead":"884711aa4ed7d518c99df3582dfbea894c4040c5","scripts":{"lint":"eslint benchmarks lib test tasks","test":"mocha --recursive test","pretest":"npm run lint"},"_npmUser":{"name":"tschaub","email":"tim.schaub@gmail.com"},"repository":{"url":"git://github.com/tschaub/mock-fs.git","type":"git"},"_npmVersion":"10.9.0","description":"A configurable mock file system.  You know, for testing.","directories":{},"_nodeVersion":"22.9.0","eslintConfig":{"env":{"es2020":true},"rules":{"prettier/prettier":["error",{"endOfLine":"auto","quoteProps":"preserve","singleQuote":true,"bracketSpacing":false}]},"extends":"tschaub","parserOptions":{"ecmaVersion":2020}},"_hasShrinkwrap":false,"devDependencies":{"chai":"^4.3.4","mocha":"^10.7.3","eslint":"^8.21.0","rimraf":"^6.0.1","semver":"^7.3.5","eslint-config-tschaub":"^14.1.2"},"_npmOperationalInternal":{"tmp":"tmp/mock-fs_5.4.1_1730390480982_0.6404950874666584","host":"s3://npm-registry-packages"},"readme":"[![Build Status](https://github.com/tschaub/mock-fs/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/tschaub/mock-fs/actions?workflow=Test)\n\n# `mock-fs`\n\nThe `mock-fs` module allows Node's built-in [`fs` module](http://nodejs.org/api/fs.html) to be backed temporarily by an in-memory, mock file system.  This lets you run tests against a set of mock files and directories instead of lugging around a bunch of test fixtures.\n\n## Example\n\nThe code below makes it so the `fs` module is temporarily backed by a mock file system with a few files and directories.\n\n```js\nconst mock = require('mock-fs');\n\nmock({\n  'path/to/fake/dir': {\n    'some-file.txt': 'file content here',\n    'empty-dir': {/** empty directory */}\n  },\n  'path/to/some.png': Buffer.from([8, 6, 7, 5, 3, 0, 9]),\n  'some/other/path': {/** another empty directory */}\n});\n```\n\nWhen you are ready to restore the `fs` module (so that it is backed by your real file system), call [`mock.restore()`](#mockrestore). Note that calling this may be **mandatory** in some cases. See [istanbuljs/nyc#324](https://github.com/istanbuljs/nyc/issues/324#issuecomment-234018654)\n\n```js\n// after a test runs\nmock.restore();\n```\n\n## Upgrading to version 4\n\nInstead of overriding all methods of the built-in `fs` module, the library now overrides `process.binding('fs')`.  The purpose of this change is to avoid conflicts with other libraries that override `fs` methods (e.g. `graceful-fs`) and to make it possible to work with multiple Node releases without maintaining copied and slightly modified versions of Node's `fs` module.\n\nBreaking changes:\n\n * The `mock.fs()` function has been removed.  This returned an object with `fs`-like methods without overriding the built-in `fs` module.\n * The object created by `fs.Stats` is no longer an instance of `fs.Stats` (though it has all the same properties and methods).\n * Lazy `require()` do not use the real filesystem.\n * Tests are no longer run in Node < 4.\n\nSome of these breaking changes may be restored in a future release.\n\n## Docs\n\n### <a id='mockconfigoptions'>`mock(config, options)`</a>\n\nConfigure the `fs` module so it is backed by an in-memory file system.\n\nCalling `mock` sets up a mock file system with two directories by default: `process.cwd()` and `os.tmpdir()` (or `os.tmpDir()` for older Node).  When called with no arguments, just these two directories are created.  When called with a `config` object, additional files, directories, and symlinks are created.  To avoid creating a directory for `process.cwd()` and `os.tmpdir()`, see the [`options`](#options) below.\n\nProperty names of the `config` object are interpreted as relative paths to resources (relative from `process.cwd()`).  Property values of the `config` object are interpreted as content or configuration for the generated resources.\n\n*Note that paths should always use forward slashes (`/`) - even on Windows.*\n\n### <a id='options'>`options`</a>\n\nThe second (optional) argument may include the properties below.\n\n * `createCwd` - `boolean` Create a directory for `process.cwd()`.  This is `true` by default.\n * `createTmp` - `boolean` Create a directory for `os.tmpdir()`.  This is `true` by default.\n\n### Loading real files & directories\n\nYou can load real files and directories into the mock system using `mock.load()`\n\n#### Notes\n\n- All stat information is duplicated (dates, permissions, etc) \n- By default, all files are lazy-loaded, unless you specify the `{lazy: false}` option\n\n#### <a id='mappingoptions'>options</a>\n\n| Option    | Type    | Default | Description |\n| --------- | ------- | ------- | ------------\n| lazy      | boolean | true    | File content isn't loaded until explicitly read\n| recursive | boolean | true    | Load all files and directories recursively\n \n#### `mock.load(path, options)`\n\n```js\nmock({\n  // Lazy-load file\n  'my-file.txt': mock.load(path.resolve(__dirname, 'assets/special-file.txt')),\n  \n  // Pre-load js file\n  'ready.js': mock.load(path.resolve(__dirname, 'scripts/ready.js'), {lazy: false}),\n\n  // Recursively loads all node_modules\n  'node_modules': mock.load(path.resolve(__dirname, '../node_modules')),\n\n  // Creates a directory named /tmp with only the files in /tmp/special_tmp_files (no subdirectories), pre-loading all content\n  '/tmp': mock.load('/tmp/special_tmp_files', {recursive: false, lazy:false}),\n\n  'fakefile.txt': 'content here'\n});\n```\n\n### Creating files\n\nWhen `config` property values are a `string` or `Buffer`, a file is created with the provided content.  For example, the following configuration creates a single file with string content (in addition to the two default directories).\n```js\nmock({\n  'path/to/file.txt': 'file content here'\n});\n```\n\nTo create a file with additional properties (owner, permissions, atime, etc.), use the [`mock.file()`](#mockfileproperties) function described below.\n\n### <a id='mockfileproperties'>`mock.file(properties)`</a>\n\nCreate a factory for new files.  Supported properties:\n\n * **content** - `string|Buffer` File contents.\n * **mode** - `number` File mode (permission and sticky bits).  Defaults to `0666`.\n * **uid** - `number` The user id.  Defaults to `process.getuid()`.\n * **gid** - `number` The group id.  Defaults to `process.getgid()`.\n * **atime** - `Date` The last file access time.  Defaults to `new Date()`.  Updated when file contents are accessed.\n * **ctime** - `Date` The last file change time.  Defaults to `new Date()`.  Updated when file owner or permissions change.\n * **mtime** - `Date` The last file modification time.  Defaults to `new Date()`.  Updated when file contents change.\n * **birthtime** - `Date` The time of file creation.  Defaults to `new Date()`.\n\nTo create a mock filesystem with a very old file named `foo`, you could do something like this:\n```js\nmock({\n  foo: mock.file({\n    content: 'file content here',\n    ctime: new Date(1),\n    mtime: new Date(1)\n  })\n});\n```\n\nNote that if you want to create a file with the default properties, you can provide a `string` or `Buffer` directly instead of calling `mock.file()`.\n\n### Creating directories\n\nWhen `config` property values are an `Object`, a directory is created.  The structure of the object is the same as the `config` object itself.  So an empty directory can be created with a simple object literal (`{}`).  The following configuration creates a directory containing two files (in addition to the two default directories):\n```js\n// note that this could also be written as\n// mock({'path/to/dir': { /** config */ }})\nmock({\n  path: {\n    to: {\n      dir: {\n        file1: 'text content',\n        file2: Buffer.from([1, 2, 3, 4])\n      }\n    }\n  }\n});\n```\n\nTo create a directory with additional properties (owner, permissions, atime, etc.), use the [`mock.directory()`](mockdirectoryproperties) function described below.\n\n### <a id='mockdirectoryproperties'>`mock.directory(properties)`</a>\n\nCreate a factory for new directories.  Supported properties:\n\n * **mode** - `number` Directory mode (permission and sticky bits).  Defaults to `0777`.\n * **uid** - `number` The user id.  Defaults to `process.getuid()`.\n * **gid** - `number` The group id.  Defaults to `process.getgid()`.\n * **atime** - `Date` The last directory access time.  Defaults to `new Date()`.\n * **ctime** - `Date` The last directory change time.  Defaults to `new Date()`.  Updated when owner or permissions change.\n * **mtime** - `Date` The last directory modification time.  Defaults to `new Date()`.  Updated when an item is added, removed, or renamed.\n * **birthtime** - `Date` The time of directory creation.  Defaults to `new Date()`.\n * **items** - `Object` Directory contents.  Members will generate additional files, directories, or symlinks.\n\nTo create a mock filesystem with a directory with the relative path `some/dir` that has a mode of `0755` and two child files, you could do something like this:\n```js\nmock({\n  'some/dir': mock.directory({\n    mode: 0755,\n    items: {\n      file1: 'file one content',\n      file2: Buffer.from([8, 6, 7, 5, 3, 0, 9])\n    }\n  })\n});\n```\n\nNote that if you want to create a directory with the default properties, you can provide an `Object` directly instead of calling `mock.directory()`.\n\n### Creating symlinks\n\nUsing a `string` or a `Buffer` is a shortcut for creating files with default properties.  Using an `Object` is a shortcut for creating a directory with default properties.  There is no shortcut for creating symlinks.  To create a symlink, you need to call the [`mock.symlink()`](#mocksymlinkproperties) function described below.\n\n### <a id='mocksymlinkproperties'>`mock.symlink(properties)`</a>\n\nCreate a factory for new symlinks.  Supported properties:\n\n * **path** - `string` Path to the source (required).\n * **mode** - `number` Symlink mode (permission and sticky bits).  Defaults to `0666`.\n * **uid** - `number` The user id.  Defaults to `process.getuid()`.\n * **gid** - `number` The group id.  Defaults to `process.getgid()`.\n * **atime** - `Date` The last symlink access time.  Defaults to `new Date()`.\n * **ctime** - `Date` The last symlink change time.  Defaults to `new Date()`.\n * **mtime** - `Date` The last symlink modification time.  Defaults to `new Date()`.\n * **birthtime** - `Date` The time of symlink creation.  Defaults to `new Date()`.\n\nTo create a mock filesystem with a file and a symlink, you could do something like this:\n```js\nmock({\n  'some/dir': {\n    'regular-file': 'file contents',\n    'a-symlink': mock.symlink({\n      path: 'regular-file'\n    })\n  }\n});\n```\n\n### Restoring the file system\n\n### <a id='mockrestore'>`mock.restore()`</a>\n\nRestore the `fs` binding to the real file system.  This undoes the effect of calling `mock()`.  Typically, you would set up a mock file system before running a test and restore the original after.  Using a test runner with `beforeEach` and `afterEach` hooks, this might look like the following:\n\n```js\nbeforeEach(function() {\n  mock({\n    'fake-file': 'file contents'\n  });\n});\nafterEach(mock.restore);\n```\n\n### Bypassing the mock file system\n\n#### <a id='mockbypass'>`mock.bypass(fn)`</a>\n\nExecute calls to the real filesystem with mock.bypass()\n\n```js\n// This file exists only on the real FS, not on the mocked FS\nconst realFilePath = '/path/to/real/file.txt';\nconst myData = mock.bypass(() => fs.readFileSync(realFilePath, 'utf-8'));\n```\n\nIf you pass an asynchronous function or a promise-returning function to `bypass()`, a promise will be returned.\n\n#### <a id='bypassasync'>Async Warning</a>\n\nAsynchronous calls are supported, however, they are not recommended as they could produce unintended consequences if \nanything else tries to access the mocked filesystem before they've completed.\n\n```js\nasync function getFileInfo(fileName) {\n  return await mock.bypass(async () => {\n    const stats = await fs.promises.stat(fileName);\n    const data = await fs.promises.readFile(fileName);\n    return {stats, data};\n  });\n}\n```\n\n## Install\n\nUsing `npm`:\n\n```\nnpm install mock-fs --save-dev\n```\n\n## Caveats\n\nWhen you require `mock-fs`, Node's own `fs` module is patched to allow the binding to the underlying file system to be swapped out.  If you require `mock-fs` *before* any other modules that modify `fs` (e.g. `graceful-fs`), the mock should behave as expected.\n\n**Note** `mock-fs` is not compatible with `graceful-fs@3.x` but works with `graceful-fs@4.x`.\n\nMock file access is controlled based on file mode where `process.getuid()` and `process.getgid()` are available (POSIX systems).  On other systems (e.g. Windows) the file mode has no effect.\n\nTested on Linux, OSX, and Windows using Node 18 through 22.  Check the tickets for a list of [known issues](https://github.com/tschaub/mock-fs/issues).\n\n### Using with Jest Snapshot Testing\n\n`.toMatchSnapshot` in [Jest](https://jestjs.io/docs/en/snapshot-testing) uses `fs` to load existing snapshots.\nIf `mockFs` is active, Jest isn't able to load existing snapshots. In such case it accepts all snapshots\nwithout diffing the old ones, which breaks the concept of snapshot testing.\n\nCalling `mock.restore()` in `afterEach` is too late and it's necessary to call it before snapshot matching:\n\n```js\nconst actual = testedFunction()\nmock.restore()\nexpect(actual).toMatchSnapshot()\n```\n\nNote: it's safe to call `mock.restore` multiple times, so it can still be called in `afterEach` and then manually\nin test cases which use snapshot testing.","publish_time":1730390481226,"_cnpm_publish_time":1730390481226,"dist-tags":{"beta":"5.0.0-beta.1","dev":"5.1.2-dev.1636402202771","latest":"5.5.0"}}