0
# Core Matcher
1
2
The `toMatchImageSnapshot` matcher is the primary function that performs image comparison against stored snapshots, integrating seamlessly with Jest's snapshot testing workflow.
3
4
## Capabilities
5
6
### toMatchImageSnapshot Matcher
7
8
Performs image comparison by creating baseline snapshots on first run and comparing subsequent images against these baselines.
9
10
```javascript { .api }
11
/**
12
* Jest matcher that compares an image buffer against a stored snapshot
13
* @param received - Image buffer (Buffer, string, or Uint8Array)
14
* @param options - Configuration options for comparison
15
*/
16
function toMatchImageSnapshot(options?: MatcherOptions): void;
17
18
interface MatcherOptions {
19
/** Custom configuration for pixelmatch or SSIM comparison algorithms */
20
customDiffConfig?: CustomDiffConfig;
21
/** Comparison method: 'pixelmatch' (default) or 'ssim' */
22
comparisonMethod?: 'pixelmatch' | 'ssim';
23
/** Custom identifier for snapshot file naming */
24
customSnapshotIdentifier?: string | CustomSnapshotIdentifierFunction;
25
/** Custom directory path for storing snapshots */
26
customSnapshotsDir?: string;
27
/** Custom directory path for storing diff images */
28
customDiffDir?: string;
29
/** Custom directory path for storing received images on failure */
30
customReceivedDir?: string;
31
/** Custom postfix for received image filenames (default: '-received') */
32
customReceivedPostfix?: string;
33
/** Store received images separately on test failure (default: false) */
34
storeReceivedOnFailure?: boolean;
35
/** Layout direction for diff images: 'horizontal' (default) or 'vertical' */
36
diffDirection?: 'horizontal' | 'vertical';
37
/** Only show diff in output image, exclude baseline and received (default: false) */
38
onlyDiff?: boolean;
39
/** Remove colors from console output (default: false) */
40
noColors?: boolean;
41
/** Threshold for test failure based on failureThresholdType (default: 0) */
42
failureThreshold?: number;
43
/** Type of threshold: 'pixel' (default) or 'percent' */
44
failureThresholdType?: 'pixel' | 'percent';
45
/** Update snapshots even when tests pass (default: false) */
46
updatePassedSnapshot?: boolean;
47
/** Gaussian blur radius in pixels for noise reduction (default: 0) */
48
blur?: number;
49
/** Run comparison in same process instead of child process (default: false) */
50
runInProcess?: boolean;
51
/** Output base64 diff string to console on failure (default: false) */
52
dumpDiffToConsole?: boolean;
53
/** Output inline diff to terminal using iTerm protocol (default: false) */
54
dumpInlineDiffToConsole?: boolean;
55
/** Allow images with different dimensions (default: false) */
56
allowSizeMismatch?: boolean;
57
/** Maximum buffer size for child process in bytes (default: 10MB) */
58
maxChildProcessBufferSizeInBytes?: number;
59
/** Path to runtime hooks file for custom image processing */
60
runtimeHooksPath?: string;
61
}
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
// Basic usage
68
expect(imageBuffer).toMatchImageSnapshot();
69
70
// With threshold configuration
71
expect(imageBuffer).toMatchImageSnapshot({
72
failureThreshold: 0.01,
73
failureThresholdType: 'percent'
74
});
75
76
// With custom snapshot identifier
77
expect(imageBuffer).toMatchImageSnapshot({
78
customSnapshotIdentifier: 'header-component-desktop'
79
});
80
81
// With custom diff configuration
82
expect(imageBuffer).toMatchImageSnapshot({
83
customDiffConfig: { threshold: 0.1 },
84
comparisonMethod: 'pixelmatch'
85
});
86
87
// SSIM comparison method
88
expect(imageBuffer).toMatchImageSnapshot({
89
comparisonMethod: 'ssim',
90
customDiffConfig: { ssim: 'fast' },
91
failureThreshold: 0.01,
92
failureThresholdType: 'percent'
93
});
94
95
// Custom directories and options
96
expect(imageBuffer).toMatchImageSnapshot({
97
customSnapshotsDir: path.join(__dirname, 'snapshots'),
98
customDiffDir: path.join(__dirname, 'diffs'),
99
storeReceivedOnFailure: true,
100
diffDirection: 'vertical'
101
});
102
```
103
104
### Image Input Handling
105
106
The matcher accepts various image input formats and converts them to PNG buffers for comparison.
107
108
```javascript { .api }
109
/**
110
* Supported image input types:
111
* - Buffer: PNG image data
112
* - string: Base64 encoded image data
113
* - Uint8Array: Raw image bytes
114
*/
115
type ImageInput = Buffer | string | Uint8Array;
116
```
117
118
### Custom Snapshot Identifier Function
119
120
Function interface for generating custom snapshot identifiers, especially useful with jest.retryTimes().
121
122
```javascript { .api }
123
interface CustomSnapshotIdentifierFunction {
124
(params: {
125
testPath: string;
126
currentTestName: string;
127
counter: number;
128
defaultIdentifier: string;
129
}): string;
130
}
131
```
132
133
**Usage Example:**
134
135
```javascript
136
expect(imageBuffer).toMatchImageSnapshot({
137
customSnapshotIdentifier: ({ testPath, currentTestName, counter }) => {
138
return `${path.basename(testPath)}-${currentTestName}-${counter}-custom`;
139
}
140
});
141
```
142
143
### Jest Integration
144
145
The matcher integrates with Jest's snapshot system and supports all Jest snapshot features:
146
147
- **Snapshot Updates**: Use `jest --updateSnapshot` or `-u` to update snapshots
148
- **CI Mode**: Prevents new snapshot creation in CI environments
149
- **Retry Support**: Compatible with `jest.retryTimes()` when using custom identifiers
150
- **Test Context**: Accesses Jest's test context including file paths and test names
151
152
**Jest Retry Example:**
153
154
```javascript
155
// Required when using jest.retryTimes()
156
jest.retryTimes(2);
157
158
it('flaky visual test', () => {
159
expect(imageBuffer).toMatchImageSnapshot({
160
customSnapshotIdentifier: 'unique-identifier-for-retry'
161
});
162
});
163
```
164
165
### Error Handling
166
167
The matcher provides detailed error messages and handles various failure scenarios:
168
169
- **Size Mismatches**: Clear reporting when image dimensions differ
170
- **Threshold Failures**: Percentage and pixel count reporting
171
- **File System Errors**: Proper error handling for directory creation and file operations
172
- **Invalid Options**: Validation of configuration parameters
173
174
**Common Error Scenarios:**
175
176
```javascript
177
// Size mismatch error
178
expect(imageBuffer).toMatchImageSnapshot({
179
allowSizeMismatch: false // Will fail if dimensions differ
180
});
181
182
// Threshold exceeded error
183
expect(imageBuffer).toMatchImageSnapshot({
184
failureThreshold: 0.001,
185
failureThresholdType: 'percent' // Will fail if > 0.1% different
186
});
187
188
// Invalid usage
189
expect(imageBuffer).not.toMatchImageSnapshot(); // Throws error - .not not supported
190
```