MCPcopy
hub / github.com/vitest-dev/vitest / useFS

Function useFS

test/test-utils/index.ts:444–508  ·  view source on GitHub ↗
(root: string, structure: T, ensureConfig = true, task?: TestContext['task'])

Source from the content-addressed store, hash-verified

442}
443
444export function useFS<T extends TestFsStructure>(root: string, structure: T, ensureConfig = true, task?: TestContext['task']) {
445 const files = new Set<string>()
446 const hasConfig = Object.keys(structure).some(file => file.includes('.config.'))
447 if (ensureConfig && !hasConfig) {
448 ;(structure as any)['./vitest.config.js'] = {}
449 }
450 for (const file in structure) {
451 const filepath = resolve(root, file)
452 files.add(filepath)
453 const content = getGeneratedFileContent(structure[file])
454 fs.mkdirSync(dirname(filepath), { recursive: true })
455 fs.writeFileSync(filepath, String(content), 'utf-8')
456 }
457 (task?.context.onTestFinished ?? onTestFinished)(() => {
458 if (process.env.VITEST_FS_CLEANUP !== 'false') {
459 fs.rmSync(root, { recursive: true, force: true })
460 }
461 })
462 return {
463 root,
464 readFile: (file: string): string => {
465 const filepath = resolve(root, file)
466 if (relative(root, filepath).startsWith('..')) {
467 throw new Error(`file ${file} is outside of the test file system`)
468 }
469 return fs.readFileSync(filepath, 'utf-8')
470 },
471 editFile: (file: string, callback: (content: string) => string) => {
472 const filepath = resolve(root, file)
473 if (!files.has(filepath)) {
474 throw new Error(`file ${file} is outside of the test file system`)
475 }
476 const content = fs.readFileSync(filepath, 'utf-8')
477 fs.writeFileSync(filepath, callback(content))
478 },
479 createFile: (file: string, content: string) => {
480 if (file.startsWith('..')) {
481 throw new Error(`file ${file} is outside of the test file system`)
482 }
483 const filepath = resolve(root, file)
484 if (files.has(filepath)) {
485 throw new Error(`file ${file} already exists in the test file system`)
486 }
487 files.add(filepath)
488 createFile(filepath, content)
489 },
490 statFile: (file: string): fs.Stats => {
491 const filepath = resolve(root, file)
492
493 if (relative(root, filepath).startsWith('..')) {
494 throw new Error(`file ${file} is outside of the test file system`)
495 }
496
497 return fs.statSync(filepath)
498 },
499 resolveFile: (file: string): string => {
500 return resolve(root, file)
501 },

Callers 4

caching.test.tsFile · 0.90
runInlineTestsFunction · 0.85
createRootFunction · 0.85
getCliConfigFunction · 0.85

Calls 8

getGeneratedFileContentFunction · 0.85
createFileFunction · 0.85
keysMethod · 0.80
resolveFunction · 0.50
relativeFunction · 0.50
callbackFunction · 0.50
addMethod · 0.45
hasMethod · 0.45

Tested by 2

createRootFunction · 0.68
getCliConfigFunction · 0.68