0
# Jest Snapshot
1
2
Jest Snapshot provides comprehensive snapshot testing functionality for the Jest testing framework, enabling developers to capture and compare serialized representations of JavaScript objects, React components, API responses, and other testable outputs. It offers powerful snapshot matchers, sophisticated serialization, property-based partial matching, and robust snapshot lifecycle management with both external snapshot files and inline snapshots.
3
4
## Package Information
5
6
- **Package Name**: jest-snapshot
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: Typically included with Jest. Can be installed directly with `npm install jest-snapshot` if needed.
10
11
## Core Imports
12
13
```typescript
14
import {
15
SnapshotState,
16
addSerializer,
17
getSerializers,
18
buildSnapshotResolver,
19
isSnapshotPath,
20
cleanup,
21
EXTENSION
22
} from "jest-snapshot";
23
```
24
25
For CommonJS:
26
27
```javascript
28
const {
29
SnapshotState,
30
addSerializer,
31
getSerializers,
32
buildSnapshotResolver,
33
isSnapshotPath,
34
cleanup,
35
EXTENSION
36
} = require("jest-snapshot");
37
```
38
39
**Note**: The snapshot matchers (`toMatchSnapshot`, `toMatchInlineSnapshot`, etc.) are not direct exports from jest-snapshot. They are automatically added to Jest's `expect()` function when using Jest.
40
41
## Basic Usage
42
43
```typescript
44
import { SnapshotState, addSerializer } from "jest-snapshot";
45
46
// Basic snapshot matching (matchers are available on expect)
47
test('component renders correctly', () => {
48
const component = render(<MyComponent />);
49
expect(component).toMatchSnapshot();
50
});
51
52
// Inline snapshot matching
53
test('simple calculation', () => {
54
const result = calculate(2, 3);
55
expect(result).toMatchInlineSnapshot(`5`);
56
});
57
58
// Property matching with snapshot
59
test('user object with partial matching', () => {
60
const user = { id: 123, name: 'John', timestamp: Date.now() };
61
expect(user).toMatchSnapshot({
62
id: expect.any(Number),
63
name: 'John'
64
// timestamp excluded from snapshot
65
});
66
});
67
68
// Error snapshot testing
69
test('function throws expected error', () => {
70
expect(() => {
71
throwError();
72
}).toThrowErrorMatchingSnapshot();
73
});
74
75
// Using SnapshotState directly (advanced usage)
76
const snapshotState = new SnapshotState('/path/to/snapshots', {
77
updateSnapshot: 'none',
78
snapshotFormat: {},
79
rootDir: '/project/root'
80
});
81
82
// Adding custom serializers
83
addSerializer({
84
test: (val) => val && val.constructor === MyClass,
85
serialize: (val) => `MyClass { ${val.name} }`
86
});
87
```
88
89
## Architecture
90
91
Jest Snapshot is built around several key architectural components:
92
93
- **Snapshot Matchers**: Jest matchers (`toMatchSnapshot`, `toMatchInlineSnapshot`) implemented by this package and added to Jest's expect function
94
- **State Management**: `SnapshotState` class manages snapshot file operations, counters, and test execution state
95
- **Path Resolution**: Flexible snapshot file location system with customizable resolvers
96
- **Serialization Engine**: Pluggable serialization system with built-in support for React components, DOM elements, and custom objects
97
- **Inline Processing**: AST-based inline snapshot embedding and updating in source code
98
- **Property Matching**: Partial object comparison with property matchers for dynamic values
99
100
## Capabilities
101
102
### Snapshot Matchers
103
104
Core snapshot testing functions for comparing values against stored snapshots. Supports both external `.snap` files and inline snapshots embedded in source code.
105
106
```typescript { .api }
107
function toMatchSnapshot(hint?: string): MatcherResult;
108
function toMatchSnapshot<U extends Record<keyof T, unknown>>(
109
propertyMatchers: Partial<U>,
110
hint?: string
111
): MatcherResult;
112
113
function toMatchInlineSnapshot(snapshot?: string): MatcherResult;
114
function toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
115
propertyMatchers: Partial<U>,
116
snapshot?: string
117
): MatcherResult;
118
```
119
120
[Snapshot Matchers](./snapshot-matchers.md)
121
122
### Error Snapshot Testing
123
124
Specialized matchers for testing error messages and exception handling with snapshot comparison.
125
126
```typescript { .api }
127
function toThrowErrorMatchingSnapshot(hint?: string): MatcherResult;
128
function toThrowErrorMatchingInlineSnapshot(snapshot?: string): MatcherResult;
129
```
130
131
[Error Snapshot Testing](./error-snapshots.md)
132
133
### State Management
134
135
The `SnapshotState` class handles snapshot file operations, maintains test execution state, and manages snapshot lifecycle.
136
137
```typescript { .api }
138
class SnapshotState {
139
constructor(snapshotPath: string, options: SnapshotStateOptions);
140
141
// Public properties
142
added: number;
143
matched: number;
144
unmatched: number;
145
updated: number;
146
expand: boolean;
147
readonly snapshotFormat: SnapshotFormat;
148
149
// Public methods
150
match(options: SnapshotMatchOptions): SnapshotReturnOptions;
151
fail(testName: string, received: unknown, key?: string): string;
152
save(): SaveStatus;
153
clear(): void;
154
getUncheckedCount(): number;
155
getUncheckedKeys(): Array<string>;
156
removeUncheckedKeys(): void;
157
markSnapshotsAsCheckedForTest(testName: string): void;
158
}
159
```
160
161
[State Management](./state-management.md)
162
163
### Path Resolution
164
165
Snapshot file path management system that resolves between test files and their corresponding snapshot files.
166
167
```typescript { .api }
168
function buildSnapshotResolver(
169
config: Config.ProjectConfig,
170
localRequire?: Promise<LocalRequire> | LocalRequire
171
): Promise<SnapshotResolver>;
172
173
function isSnapshotPath(path: string): boolean;
174
175
const EXTENSION: string; // 'snap'
176
177
interface SnapshotResolver {
178
resolveSnapshotPath(testPath: string, snapshotExtension?: string): string;
179
resolveTestPath(snapshotPath: string, snapshotExtension?: string): string;
180
testPathForConsistencyCheck: string;
181
}
182
```
183
184
[Path Resolution](./path-resolution.md)
185
186
### Serialization and Plugins
187
188
Pluggable serialization system for customizing how values are converted to snapshot strings.
189
190
```typescript { .api }
191
function addSerializer(plugin: PrettyFormatPlugin): void;
192
function getSerializers(): PrettyFormatPlugins;
193
194
// Plugin types from pretty-format
195
interface PrettyFormatPlugin {
196
serialize(
197
val: any,
198
config: Config,
199
indentation: string,
200
depth: number,
201
refs: Refs,
202
printer: Printer
203
): string;
204
test(val: any): boolean;
205
}
206
207
type PrettyFormatPlugins = PrettyFormatPlugin[];
208
```
209
210
[Serialization and Plugins](./serialization.md)
211
212
### Cleanup Operations
213
214
Utility functions for maintaining snapshot files and removing orphaned snapshots.
215
216
```typescript { .api }
217
function cleanup(
218
fileSystem: FileSystem,
219
update: Config.SnapshotUpdateState,
220
snapshotResolver: SnapshotResolver,
221
testPathIgnorePatterns?: string[]
222
): {
223
filesRemoved: number;
224
filesRemovedList: Array<string>;
225
};
226
```
227
228
[Cleanup Operations](./cleanup.md)
229
230
## Types
231
232
### Core Interfaces
233
234
```typescript { .api }
235
interface Context extends MatcherContext {
236
snapshotState: SnapshotState;
237
testFailing?: boolean;
238
}
239
240
interface SnapshotMatchers<R extends void | Promise<void>, T> {
241
toMatchSnapshot(hint?: string): R;
242
toMatchSnapshot<U extends Record<keyof T, unknown>>(
243
propertyMatchers: Partial<U>,
244
hint?: string
245
): R;
246
toMatchInlineSnapshot(snapshot?: string): R;
247
toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
248
propertyMatchers: Partial<U>,
249
snapshot?: string
250
): R;
251
toThrowErrorMatchingSnapshot(hint?: string): R;
252
toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
253
}
254
255
interface FileSystem {
256
exists(path: string): boolean;
257
matchFiles(pattern: RegExp | string): Array<string>;
258
}
259
260
type SnapshotFormat = Omit<PrettyFormatOptions, 'compareKeys'>;
261
262
interface InlineSnapshot {
263
snapshot: string;
264
frame: Frame;
265
node?: Expression;
266
}
267
```
268
269
### Configuration Types
270
271
```typescript { .api }
272
interface SnapshotStateOptions {
273
readonly updateSnapshot: Config.SnapshotUpdateState;
274
readonly prettierPath?: string | null;
275
readonly expand?: boolean;
276
readonly snapshotFormat: SnapshotFormat;
277
readonly rootDir: string;
278
}
279
280
interface SnapshotMatchOptions {
281
readonly testName: string;
282
readonly received: unknown;
283
readonly key?: string;
284
readonly inlineSnapshot?: string;
285
readonly isInline: boolean;
286
readonly error?: Error;
287
readonly testFailing?: boolean;
288
}
289
290
interface SnapshotReturnOptions {
291
readonly actual: string;
292
readonly count: number;
293
readonly expected?: string;
294
readonly key: string;
295
readonly pass: boolean;
296
}
297
298
interface SaveStatus {
299
deleted: boolean;
300
saved: boolean;
301
}
302
303
interface MatchSnapshotConfig {
304
context: Context;
305
hint?: string;
306
inlineSnapshot?: string;
307
isInline: boolean;
308
matcherName: string;
309
properties?: object;
310
received: any;
311
}
312
```