Jest: How do you change the Snapshot Folder?
Snapshots are one of my favourites features in Jest, unfortunately snap
files and __snapshots__
folders may create visual pollution making your folders a little messy.
Luckily Jest lets you configure where you want to place your snapshots.
What do we want?
Move the snap
files and __snapshots__
folders from the default position into my-snapshot-folder
.
Current:
.
└── src
└── components
└── accordion
├── tests
│ ├── accordion.spec.ts
│ └── __snapshots__
│ └── accordion.spec.ts.snap
└── accordion.tsx
Wanted:
.
├── src
│ └── components
│ └── accordion
│ ├── tests
│ │ └── accordion.spec.ts
│ └── accordion.tsx
│
└── my-snapshot-folder
└── __snapshots__
└── components
└── accordion
└── tests
└── accordion.spec.ts.snap
For this, we’ll have a 2 steps procedure:
- add a snapshotResolver into jest.config.js
- configure the snapshotResolver
Step 1: set snapshotResolver
into jest.config.js
/** @type {import('jest').Config} */
const config = {
.
.
.
snapshotResolver: '<rootDir>/my-snapshot-folder/snapshotResolver.js'
.
.
.
};
module.exports = config;
Basically snapshotResolver tells Jest, “Hey, for the snapshots check snapshotResolver.js
for instructions”.
Init Jest:
You can init jest.config.js
with npm init jest@latest
.
Step 2: configure snapshotResolver.js
// use path to avoid issues on Linux vs Max vs Windows
const path = require('node:path');
const testFolder = 'src' + path.sep;
const snapshotFolder = 'my-snapshot-folder' + path.sep + '__snapshots__' + path.sep;
module.exports = {
/*
testPathForConsistencyCheck
Tells how your tests look like as a path.
Eg:
when:
src/components/accordion/tests/accordion.spec.ts
testPathForConsistencyCheck:
tests/example.spec.ts
when:
src/components/accordion/__tests__/accordion.test.js
testPathForConsistencyCheck:
__tests__/example.test.js
*/
testPathForConsistencyCheck: 'test/example.spec.js'
/*
resolveSnapshotPath
Tells where are the snapshots from a test
Eg:
when:
src/components/accordion/tests/accordion.spec.ts
snapshot:
my-snapshot-folder/__snapshots__/components/accordion/tests/accordion.spec.ts.snap
*/
resolveSnapshotPath: (testFilePath, snapshotExtension) => {
return testFilePath.replace(testFolder, snapshotFolder) + snapshotExtension;
},
/*
resolveTestPath
Tells where are the test from a snapshot
Eg:
when:
my-snapshot-folder/__snapshots__/components/accordion/tests/accordion.spec.ts.snap
test:
src/components/accordion/tests/accordion.spec.ts
*/
resolveTestPath: (snapshotFilePath, snapshotExtension) => {
return snapshotFilePath
.replace(snapshotFolder, testFolder)
.slice(0, -snapshotExtension.length);
},
};
Summary
Snapshots are an amazing feature in Jest but they can be messy to deal with. Fortuantely, you can use a snapshotResolver
to better fit your needs.
In the example, we saw how to move snapshots in a custom folder and related config files: jest.config.js
, and snapshotResolver.js
.
If you are interested in the topic, see Configuring Jest: snapshotResolver.