reactjstypescriptjestjssnapshot

How to centralize snapshots folder in a React project?


I am in a project where I have to build a React UI. As it is a small project & I'm alone on it, I'd try to develop it with TypeScript & a TDD approach.

I learnt practises, installed Jest & Enzyme. What I understood is there is a __snapshot__ directory wherever there is a snpashot test. Is there a way to centralize all the snapshots in a specific path?

The idea behind the question is to keep the project folder as clean & readable as possible, without adding a __snapshot__ folder in each component folder.

One way to get a convenient behaviour is to store all tests in a src/tests folder, to get a src/tests/__snapshots__ folder, but I'd rather to keep components tests in components folders.


Solution

  • You need to create custom snapshot resolver in your jest.config file. Link has an example of code which does what you want.

    module.exports = {
    
      // resolves from test to snapshot path
      resolveSnapshotPath: (testPath, snapshotExtension) =>
      testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
    
      // resolves from snapshot to test path
      resolveTestPath: (snapshotFilePath, snapshotExtension) =>  
        snapshotFilePath
        .replace('__snapshots__', '__tests__')
        .slice(0, -snapshotExtension.length),
    
      // Example test path, used for preflight consistency check of the implementation above
      testPathForConsistencyCheck: 'some/__tests__/example.test.js',
    };