{"id":13547875,"url":"https://github.com/tschaub/mock-fs","last_synced_at":"2025-05-13T17:14:14.557Z","repository":{"id":11718458,"uuid":"14238815","full_name":"tschaub/mock-fs","owner":"tschaub","description":"Configurable mock for the fs module","archived":false,"fork":false,"pushed_at":"2025-05-08T20:08:14.000Z","size":1594,"stargazers_count":918,"open_issues_count":70,"forks_count":87,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-05-08T21:23:28.498Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://npmjs.org/package/mock-fs","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tschaub.png","metadata":{"files":{"readme":"readme.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"license.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2013-11-08T16:54:54.000Z","updated_at":"2025-05-08T20:08:17.000Z","dependencies_parsed_at":"2024-06-18T11:14:31.460Z","dependency_job_id":"d5134113-206b-4d76-bf26-f197e552f14d","html_url":"https://github.com/tschaub/mock-fs","commit_stats":{"total_commits":590,"total_committers":46,"mean_commits":"12.826086956521738","dds":"0.36101694915254234","last_synced_commit":"00cc7b52e41f71fc757e91c43bc42f803efa12e8"},"previous_names":[],"tags_count":80,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tschaub%2Fmock-fs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tschaub%2Fmock-fs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tschaub%2Fmock-fs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tschaub%2Fmock-fs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tschaub","download_url":"https://codeload.github.com/tschaub/mock-fs/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253171261,"owners_count":21865293,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T12:01:02.546Z","updated_at":"2025-05-13T17:14:09.545Z","avatar_url":"https://github.com/tschaub.png","language":"JavaScript","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 \u003c 4.\n\nSome of these breaking changes may be restored in a future release.\n\n## Docs\n\n### \u003ca id='mockconfigoptions'\u003e`mock(config, options)`\u003c/a\u003e\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### \u003ca id='options'\u003e`options`\u003c/a\u003e\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 \u0026 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#### \u003ca id='mappingoptions'\u003eoptions\u003c/a\u003e\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### \u003ca id='mockfileproperties'\u003e`mock.file(properties)`\u003c/a\u003e\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### \u003ca id='mockdirectoryproperties'\u003e`mock.directory(properties)`\u003c/a\u003e\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### \u003ca id='mocksymlinkproperties'\u003e`mock.symlink(properties)`\u003c/a\u003e\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### \u003ca id='mockrestore'\u003e`mock.restore()`\u003c/a\u003e\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#### \u003ca id='mockbypass'\u003e`mock.bypass(fn)`\u003c/a\u003e\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(() =\u003e 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#### \u003ca id='bypassasync'\u003eAsync Warning\u003c/a\u003e\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 () =\u003e {\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.","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftschaub%2Fmock-fs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftschaub%2Fmock-fs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftschaub%2Fmock-fs/lists"}