Skip to content

trimCommonFolder

trimCommonFolder removes a common folder prefix from a file path to generate a shorter snapshot sub-path.

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:

vitest.config.ts
import { trimCommonFolder, vis } from 'vitest-plugin-vis/config'
export default defineConfig({
plugins: [
vis({
snapshotSubpath: ({ subpath }) => trimCommonFolder(subpath),
}),
],
})
function trimCommonFolder(suiteName: string): string

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:

  • tests
  • test
  • src
  • source
  • js
  • ts
  • lib

These pairs come from the tests of the function.

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'
// Unrecognized folder
trimCommonFolder('app/components/button') // 'app/components/button'
// No slash separator
trimCommonFolder('index.ts') // 'index.ts'
trimCommonFolder('SRC/components/button') // 'SRC/components/button'
trimCommonFolder('app/src/button') // 'app/src/button'
trimCommonFolder('src/src/button') // 'src/button'

Each .. is replaced with __:

trimCommonFolder('../components/button') // '__/components/button'
trimCommonFolder('../../components/button') // '__/__/components/button'

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.ts
export default defineConfig({
plugins: [
vis({
snapshotSubpath: ({ subpath }) => customTrimFolder(subpath),
}),
],
})