Snapshot Testing
Snapshot testing is one of those features that sounds weird until you try it. Instead of writing assertions, you tell Jest to save the output and compare it next time. If anything changes, the test fails.
Trust me, once you start using snapshots for things like UI components and config objects, you will wonder how you lived without them.
Basic Snapshot Test
You call toMatchSnapshot on any value. The first time it runs, Jest saves a snapshot file. The next time, it compares against that saved snapshot.
function getConfig() {
return {
name: 'MyApp',
version: '1.0.0',
debug: false
};
}
it('matches config snapshot', () => {
expect(getConfig()).toMatchSnapshot();
});
The first run creates a __snapshots__ folder with the saved output. Every subsequent run compares against it. If your config changes, the test fails and shows you exactly what changed.
Updating Snapshots
When you intentionally change something, update the snapshot with the -u flag.
// terminal
npx jest --updateSnapshot
This regenerates the snapshot files. Use this when your changes are intentional, not when you accidentally broke something.
Inline Snapshots
Inline snapshots put the snapshot right in the test file instead of a separate file. Handy for small values.
it('formats user object', () => {
expect(formatUser({ name: 'Alice', age: 25 })).toMatchInlineSnapshot(`
{
"displayName": "Alice (25)",
"isValid": true
}
`);
});
When to Use Snapshots
Snapshots are great for complex objects that are tedious to assert field by field. Config objects, UI component output, API response shapes. They are not great for everything though. Simple values are better tested with toBe or toEqual.
Try it Yourself →Key Takeaways
- toMatchSnapshot saves and compares output automatically
- Use --updateSnapshot when changes are intentional
- Inline snapshots keep the snapshot in the test file
- Great for complex objects and UI component output
- Not ideal for simple primitive values