0
# State Management
1
2
The `SnapshotState` class manages snapshot file operations, maintains test execution state, and handles the lifecycle of snapshot data including creation, updating, and cleanup of snapshot files.
3
4
## Capabilities
5
6
### SnapshotState Class
7
8
Core class that manages snapshot operations for a single snapshot file, tracking test results and handling file I/O operations.
9
10
```typescript { .api }
11
/**
12
* Manages snapshot operations for a single snapshot file
13
* @param snapshotPath - Path to the snapshot file
14
* @param options - Configuration options for snapshot behavior
15
*/
16
class SnapshotState {
17
constructor(snapshotPath: string, options: SnapshotStateOptions);
18
19
// State counters
20
added: number; // Number of snapshots added in this test run
21
matched: number; // Number of snapshots that matched existing ones
22
unmatched: number; // Number of snapshots that didn't match
23
updated: number; // Number of snapshots updated in this test run
24
25
// Configuration
26
expand: boolean; // Whether to expand diff output
27
snapshotFormat: SnapshotFormat; // Formatting options for snapshots
28
29
// Core methods
30
match(options: SnapshotMatchOptions): SnapshotReturnOptions;
31
fail(testName: string, received: unknown, key?: string): string;
32
save(): SaveStatus;
33
clear(): void;
34
getUncheckedCount(): number;
35
getUncheckedKeys(): Array<string>;
36
removeUncheckedKeys(): void;
37
markSnapshotsAsCheckedForTest(testName: string): void;
38
}
39
```
40
41
**Usage Examples:**
42
43
```typescript
44
import { SnapshotState } from "jest-snapshot";
45
46
// Create snapshot state for a test file
47
const snapshotState = new SnapshotState(
48
'/path/to/__snapshots__/test.spec.js.snap',
49
{
50
updateSnapshot: 'none', // 'all' | 'new' | 'none'
51
expand: false,
52
snapshotFormat: {
53
printWidth: 80,
54
tabWidth: 2,
55
useTabs: false
56
},
57
rootDir: '/project/root',
58
prettierPath: null
59
}
60
);
61
62
// Match a value against a snapshot
63
const result = snapshotState.match({
64
testName: 'should render component correctly',
65
received: '<div>Hello World</div>',
66
isInline: false
67
});
68
69
console.log(result.pass); // true if snapshot matches
70
console.log(result.actual); // serialized received value
71
console.log(result.expected); // existing snapshot content
72
73
// Save snapshots to file
74
const saveResult = snapshotState.save();
75
console.log(saveResult.saved); // true if snapshots were written
76
console.log(saveResult.deleted); // true if file was deleted
77
```
78
79
### Snapshot Matching
80
81
The `match` method compares received values against stored snapshots and handles snapshot creation or updates.
82
83
```typescript { .api }
84
/**
85
* Matches a received value against a stored snapshot
86
* @param options - Match configuration including test name and received value
87
* @returns Match result with pass/fail status and snapshot content
88
*/
89
match(options: SnapshotMatchOptions): SnapshotReturnOptions;
90
91
interface SnapshotMatchOptions {
92
readonly testName: string; // Full test name including describe blocks
93
readonly received: unknown; // Value to compare against snapshot
94
readonly key?: string; // Optional custom snapshot key
95
readonly inlineSnapshot?: string; // Existing inline snapshot content
96
readonly isInline: boolean; // Whether this is an inline snapshot
97
readonly error?: Error; // Error context for better reporting
98
readonly testFailing?: boolean; // Whether the test is expected to fail
99
}
100
101
interface SnapshotReturnOptions {
102
readonly actual: string; // Serialized received value
103
readonly count: number; // Snapshot count for this test name
104
readonly expected?: string; // Existing snapshot content (undefined for new)
105
readonly key: string; // Generated snapshot key
106
readonly pass: boolean; // Whether the match succeeded
107
}
108
```
109
110
**Match Behavior:**
111
112
```typescript
113
// New snapshot (first time)
114
const result = snapshotState.match({
115
testName: 'new test',
116
received: { id: 1, name: 'John' },
117
isInline: false
118
});
119
// result.pass = true, result.expected = undefined, snapshotState.added++
120
121
// Existing snapshot (matches)
122
const result = snapshotState.match({
123
testName: 'existing test',
124
received: 'expected value',
125
isInline: false
126
});
127
// result.pass = true, result.expected = 'expected value', snapshotState.matched++
128
129
// Existing snapshot (doesn't match)
130
const result = snapshotState.match({
131
testName: 'existing test',
132
received: 'different value',
133
isInline: false
134
});
135
// result.pass = false, shows diff, snapshotState.unmatched++
136
```
137
138
### Failure Handling
139
140
The `fail` method handles snapshot failures and generates unique keys for failed snapshots.
141
142
```typescript { .api }
143
/**
144
* Records a snapshot failure and generates a unique key
145
* @param testName - Name of the failing test
146
* @param received - Value that failed to match
147
* @param key - Optional custom snapshot key
148
* @returns Unique snapshot key for the failure
149
*/
150
fail(testName: string, received: unknown, key?: string): string;
151
```
152
153
**Usage Example:**
154
155
```typescript
156
// Record a property matcher failure
157
const failKey = snapshotState.fail(
158
'user object test',
159
{ id: 123, name: 'John', timestamp: 1234567890 }
160
);
161
// Returns something like "user object test 1"
162
// Increments failure counter for this test name
163
```
164
165
### File Operations
166
167
Save snapshots to disk and manage unchecked snapshots.
168
169
```typescript { .api }
170
/**
171
* Saves all snapshots to disk
172
* @returns Status indicating whether file was saved or deleted
173
*/
174
save(): SaveStatus;
175
176
/**
177
* Gets count of unchecked snapshots (snapshots not used in current test run)
178
* @returns Number of unchecked snapshots
179
*/
180
getUncheckedCount(): number;
181
182
/**
183
* Gets array of unchecked snapshot keys
184
* @returns Array of snapshot keys that weren't checked in current test run
185
*/
186
getUncheckedKeys(): Array<string>;
187
188
/**
189
* Removes unchecked snapshots from the snapshot data
190
*/
191
removeUncheckedKeys(): void;
192
193
/**
194
* Resets all counters and snapshot data to initial state
195
*/
196
clear(): void;
197
198
/**
199
* Marks all snapshots for a specific test as checked
200
* @param testName - Name of the test to mark snapshots as checked
201
*/
202
markSnapshotsAsCheckedForTest(testName: string): void;
203
204
interface SaveStatus {
205
deleted: boolean; // True if snapshot file was deleted (no snapshots)
206
saved: boolean; // True if snapshot file was written
207
}
208
```
209
210
**File Management Example:**
211
212
```typescript
213
// After running tests, save snapshots
214
const saveStatus = snapshotState.save();
215
216
if (saveStatus.saved) {
217
console.log('Snapshots saved to file');
218
}
219
220
if (saveStatus.deleted) {
221
console.log('Snapshot file deleted (no snapshots remaining)');
222
}
223
224
// Clean up unused snapshots
225
const uncheckedCount = snapshotState.getUncheckedCount();
226
if (uncheckedCount > 0) {
227
console.log(`${uncheckedCount} unused snapshots found`);
228
snapshotState.removeUncheckedKeys();
229
}
230
```
231
232
### Inline Snapshot Handling
233
234
Special handling for inline snapshots that are embedded in source code.
235
236
```typescript
237
// Inline snapshot matching
238
const result = snapshotState.match({
239
testName: 'inline test',
240
received: 'test value',
241
isInline: true,
242
inlineSnapshot: '"test value"' // existing inline snapshot
243
});
244
245
// For new inline snapshots
246
const result = snapshotState.match({
247
testName: 'new inline test',
248
received: { data: 'value' },
249
isInline: true
250
// inlineSnapshot omitted for new snapshots
251
});
252
```
253
254
## Configuration Types
255
256
```typescript { .api }
257
interface SnapshotStateOptions {
258
readonly updateSnapshot: Config.SnapshotUpdateState; // 'all' | 'new' | 'none'
259
readonly prettierPath?: string | null; // Path to prettier for formatting
260
readonly expand?: boolean; // Expand diff output
261
readonly snapshotFormat: SnapshotFormat; // Snapshot serialization options
262
readonly rootDir: string; // Project root directory
263
}
264
265
type SnapshotFormat = Omit<PrettyFormatOptions, 'compareKeys'>;
266
267
// Update modes:
268
// 'all' - Update all snapshots (--updateSnapshot)
269
// 'new' - Only create new snapshots (--ci)
270
// 'none' - Don't update any snapshots (default)
271
```
272
273
## Error Scenarios
274
275
```typescript
276
// Missing snapshot path
277
new SnapshotState('', options);
278
// Error: Invalid snapshot path
279
280
// Invalid update mode
281
new SnapshotState(path, { updateSnapshot: 'invalid' });
282
// Error: Invalid updateSnapshot value
283
284
// File system errors
285
snapshotState.save();
286
// May throw filesystem errors if directory not writable
287
```