Quick Start
import { createFixture } from 'fs-fixture'
// From object — keys are paths, values are content
const fixture = await createFixture({
'package.json': JSON.stringify({ name: 'test' }),
'src/index.js': 'export default 42',
})
// Use fixture.path, fixture.readFile(), etc.
await fixture.rm() // Cleanup when done
Auto-cleanup with using (TypeScript 5.2+):
await using fixture = await createFixture({ 'file.txt': 'content' })
// Automatically cleaned up when scope exits
createFixture(source?, options?)
| Source |
Behavior |
{ path: content } |
Create files from object. Nested objects create directories. |
'./path' |
Copy template directory into fixture |
(fixture) => ... |
Run complex, imperative, or ordered setup and optionally return a FileTree |
| (omitted) |
Empty temporary directory |
| Option |
Type |
Default |
Description |
tempDir |
string | URL |
os.tmpdir() |
Custom parent directory |
templateFilter |
(src, dest) => boolean |
— |
Filter files when copying template |
FsFixture Methods
| Method |
Description |
fixture.path |
Absolute path to fixture root |
getPath(...paths) |
Resolve path relative to fixture root |
exists(path?) |
Check existence (returns boolean) |
readFile(path, encoding?) |
Read file — 'utf8' returns string, omit for Buffer |
writeFile(path, content) |
Write string or Buffer |
readJson<T>(path) |
Read and parse JSON with type parameter |
writeJson(path, data, space?) |
Write JSON (default: 2-space indent, 0 for minified) |
readdir(), readdir(path, options?) |
List fixture root or directory. Pass '' for root options. { withFileTypes: true } returns Dirent[]. |
mkdir(path) |
Create directory recursively |
cp(source, dest?) |
Copy external file/directory into fixture |
mv(source, dest) |
Move or rename within fixture |
rm(path?) |
Delete path, or entire fixture if omitted |
FileTree Values
| Type |
Example |
string |
'file content' |
Buffer |
Buffer.from([0x89, 0x50]) |
| Nested object |
{ dir: { 'file.txt': 'content' } } |
| Function |
({ fixturePath, filePath, getPath, symlink }) => symlink('./target') |
Path syntax — these are equivalent:
// Nested objects
{ src: { utils: { 'helper.js': 'code' } } }
// Slash-separated keys
{ 'src/utils/helper.js': 'code' }
[!TIP]
Slash-separated keys can also group a shared prefix:
await createFixture({
'file.js': 'import { a } from "my-pkg";',
'node_modules/my-pkg': {
'package.json': JSON.stringify({
name: 'my-pkg',
type: 'module',
exports: './index.js'
}),
'index.js': 'export const a = 1;'
}
})
Patterns
Choosing a source
- Prefer a FileTree for files and directories.
- Use an initializer function for complex, imperative, or ordered setup, such as initializing a Git repository or running a project setup helper.
- Return a FileTree from an initializer for declarative files that should be created after setup completes.
- Use a FileTree entry function for isolated dynamic file content.
Symlinks
const fixture = await createFixture({
'target.txt': 'real file',
'link.txt': ({ symlink }) => symlink('./target.txt'),
'node_modules/pkg': ({ symlink }) => symlink(process.cwd()),
})
Dynamic content
const fixture = await createFixture({
'info.txt': ({ fixturePath }) => `Root: ${fixturePath}`,
})
Initialization
const fixture = await createFixture(async ({ path, writeJson }) => {
await writeJson('package.json', { name: 'test-package' })
// Test-specific setup that needs the fixture path.
await initializeProject(path)
return {
'src/index.js': 'export default 42',
}
})
The initializer receives the fixture before it is returned. It contains setup with the fixture it configures and can return a FileTree to create after setup completes. Returned files overwrite regular files created during setup, but the tree does not replace the fixture directory. If setup fails, fs-fixture removes the fixture before it rethrows the error.
Related
Commonly used with manten test framework.
1---2name: fs-fixture3description: Create disposable file system test fixtures from objects, templates, or empty directories with automatic cleanup. Use when writing tests that need temporary files, directories, symlinks, or JSON fixtures on disk. Keywords - fs, tmp, temp, fixture, testing utility, cleanup, dispose.4metadata:5 source: https://skillmd.com/skills/privatenumber/fs-fixture6---78## Quick Start910```ts11import { createFixture } from 'fs-fixture'1213// From object — keys are paths, values are content14const fixture = await createFixture({15 'package.json': JSON.stringify({ name: 'test' }),16 'src/index.js': 'export default 42',17})1819// Use fixture.path, fixture.readFile(), etc.20await fixture.rm() // Cleanup when done21```2223Auto-cleanup with `using` (TypeScript 5.2+):24```ts25await using fixture = await createFixture({ 'file.txt': 'content' })26// Automatically cleaned up when scope exits27```2829## createFixture(source?, options?)3031| Source | Behavior |32|--------|----------|33| `{ path: content }` | Create files from object. Nested objects create directories. |34| `'./path'` | Copy template directory into fixture |35| `(fixture) => ...` | Run complex, imperative, or ordered setup and optionally return a FileTree |36| _(omitted)_ | Empty temporary directory |3738| Option | Type | Default | Description |39|--------|------|---------|-------------|40| `tempDir` | `string \| URL` | `os.tmpdir()` | Custom parent directory |41| `templateFilter` | `(src, dest) => boolean` | — | Filter files when copying template |4243## FsFixture Methods4445| Method | Description |46|--------|-------------|47| `fixture.path` | Absolute path to fixture root |48| `getPath(...paths)` | Resolve path relative to fixture root |49| `exists(path?)` | Check existence (returns `boolean`) |50| `readFile(path, encoding?)` | Read file — `'utf8'` returns `string`, omit for `Buffer` |51| `writeFile(path, content)` | Write string or Buffer |52| `readJson<T>(path)` | Read and parse JSON with type parameter |53| `writeJson(path, data, space?)` | Write JSON (default: 2-space indent, `0` for minified) |54| `readdir()`, `readdir(path, options?)` | List fixture root or directory. Pass `''` for root options. `{ withFileTypes: true }` returns Dirent[]. |55| `mkdir(path)` | Create directory recursively |56| `cp(source, dest?)` | Copy external file/directory into fixture |57| `mv(source, dest)` | Move or rename within fixture |58| `rm(path?)` | Delete path, or entire fixture if omitted |5960## FileTree Values6162| Type | Example |63|------|---------|64| `string` | `'file content'` |65| `Buffer` | `Buffer.from([0x89, 0x50])` |66| Nested object | `{ dir: { 'file.txt': 'content' } }` |67| Function | `({ fixturePath, filePath, getPath, symlink }) => symlink('./target')` |6869Path syntax — these are equivalent:70```ts71// Nested objects72{ src: { utils: { 'helper.js': 'code' } } }7374// Slash-separated keys75{ 'src/utils/helper.js': 'code' }76```7778> [!TIP]79> Slash-separated keys can also group a shared prefix:80>81> ```ts82> await createFixture({83> 'file.js': 'import { a } from "my-pkg";',84>85> 'node_modules/my-pkg': {86> 'package.json': JSON.stringify({87> name: 'my-pkg',88> type: 'module',89> exports: './index.js'90> }),91> 'index.js': 'export const a = 1;'92> }93> })94> ```9596## Patterns9798### Choosing a source99100- Prefer a FileTree for files and directories.101- Use an initializer function for complex, imperative, or ordered setup, such as initializing a Git repository or running a project setup helper.102- Return a FileTree from an initializer for declarative files that should be created after setup completes.103- Use a FileTree entry function for isolated dynamic file content.104105### Symlinks106```ts107const fixture = await createFixture({108 'target.txt': 'real file',109 'link.txt': ({ symlink }) => symlink('./target.txt'),110 'node_modules/pkg': ({ symlink }) => symlink(process.cwd()),111})112```113114### Dynamic content115```ts116const fixture = await createFixture({117 'info.txt': ({ fixturePath }) => `Root: ${fixturePath}`,118})119```120121### Initialization122```ts123const fixture = await createFixture(async ({ path, writeJson }) => {124 await writeJson('package.json', { name: 'test-package' })125126 // Test-specific setup that needs the fixture path.127 await initializeProject(path)128129 return {130 'src/index.js': 'export default 42',131 }132})133```134135The initializer receives the fixture before it is returned. It contains setup with the fixture it configures and can return a FileTree to create after setup completes. Returned files overwrite regular files created during setup, but the tree does not replace the fixture directory. If setup fails, fs-fixture removes the fixture before it rethrows the error.136137## Related138139Commonly used with `manten` test framework.