DEV Community

Cory Robinson
Cory Robinson

Posted on

Custom Jest Snapshots Directory Setup

When you want to place your component test files right next to the component's but you don't want your directories littered with __snapshots__/ dirs:

// __snapshots__/snapshotResolver.js

module.exports = {
  resolveSnapshotPath: (testPath, snapshotExtension) =>
    testPath
      .replace(
        /\.test\.([tj]sx?)/, 
        `.test${snapshotExtension}`
      )
      .replace(
        /src([/\\]components)/, 
        '__snapshots__'
      ),

  resolveTestPath: (snapshotFilePath, snapshotExtension) =>
    snapshotFilePath
      .replace(snapshotExtension, '.js')
      .replace('__snapshots__', 'src/components'),

  testPathForConsistencyCheck: 'src/components/some.test.js',
}
// jest.config.js

module.exports = {
  preset: 'react-native', // optional depending on your project

  snapshotResolver: './__snapshots__/snapshotResolver.js',

  testMatch: [
    '**/__tests__/**/?(*.)+(spec|test).(js|ts|tsx)', 
    '**/?(*.)+(spec|test).(js|ts|tsx)'
  ],
}

Top comments (0)