trimCommonFolder
trimCommonFolder removes a common folder prefix from a file path to generate a shorter snapshot sub-path.
Purpose
Section titled “Purpose”Test files often sit in common directories such as src or tests.
trimCommonFolder removes these prefixes to create shorter, more meaningful snapshot directory structures.
The default snapshotSubpath option of vis uses this function.
You can also use it in your own snapshotSubpath:
import { trimCommonFolder, vis } from 'vitest-plugin-vis/config'
export default defineConfig({ plugins: [ vis({ snapshotSubpath: ({ subpath }) => trimCommonFolder(subpath), }), ],})Function signature
Section titled “Function signature”function trimCommonFolder(suiteName: string): stringSupported common folders
Section titled “Supported common folders”It removes the first path segment when it is one of these.
The match is exact and case-sensitive, so SRC/components/button is not trimmed.
Only the first segment is checked:
teststestsrcsourcejstslib
Examples
Section titled “Examples”These pairs come from the tests of the function.
Trimming common folders
Section titled “Trimming common folders”trimCommonFolder('src/components/button') // 'components/button'trimCommonFolder('source/components/button') // 'components/button'trimCommonFolder('tests/unit/button') // 'unit/button'trimCommonFolder('test/unit/button') // 'unit/button'trimCommonFolder('js/components/button') // 'components/button'trimCommonFolder('ts/components/button') // 'components/button'trimCommonFolder('lib/components/button') // 'components/button'No trimming
Section titled “No trimming”// Unrecognized foldertrimCommonFolder('app/components/button') // 'app/components/button'
// No slash separatortrimCommonFolder('index.ts') // 'index.ts'Case and nesting
Section titled “Case and nesting”trimCommonFolder('SRC/components/button') // 'SRC/components/button'trimCommonFolder('app/src/button') // 'app/src/button'trimCommonFolder('src/src/button') // 'src/button'Parent folders
Section titled “Parent folders”Each .. is replaced with __:
trimCommonFolder('../components/button') // '__/components/button'trimCommonFolder('../../components/button') // '__/__/components/button'Custom implementation
Section titled “Custom implementation”snapshotSubpath accepts any function that takes { subpath } and returns a string.
For example, to trim your own list of folders:
function customTrimFolder(suiteName: string) { const customFolders = ['app', 'pages', 'components'] const suiteDir = suiteName.split('/', 1)[0]!
if (customFolders.includes(suiteDir)) { return suiteName.slice(suiteDir.length + 1) }
return suiteName}
// vitest.config.tsexport default defineConfig({ plugins: [ vis({ snapshotSubpath: ({ subpath }) => customTrimFolder(subpath), }), ],})Related
Section titled “Related”- vis config: main plugin configuration.
- Customizing the snapshot path