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 (exact, lowercase match):

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

These pairs come from the spec 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'

Each .. is replaced with __:

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

You can write your own trimming logic and use it as snapshotSubpath:

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),
}),
],
})