/
index.ts
311 lines (280 loc) · 7.56 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs';
import {Config, Matchers, Snapshot} from '@jest/types';
import {FS as HasteFS} from 'jest-haste-map';
import diff from 'jest-diff';
import {EXPECTED_COLOR, matcherHint, RECEIVED_COLOR} from 'jest-matcher-utils';
import {
buildSnapshotResolver,
isSnapshotPath,
EXTENSION,
} from './snapshot_resolver';
import SnapshotState from './State';
import {addSerializer, getSerializers} from './plugins';
import * as utils from './utils';
type Context = Matchers.MatcherState & {
snapshotState: SnapshotState;
};
const fileExists = (filePath: Config.Path, hasteFS: HasteFS): boolean =>
hasteFS.exists(filePath) || fs.existsSync(filePath);
const cleanup = (
hasteFS: HasteFS,
update: Config.SnapshotUpdateState,
snapshotResolver: Snapshot.SnapshotResolver,
) => {
const pattern = '\\.' + EXTENSION + '$';
const files = hasteFS.matchFiles(pattern);
const filesRemoved = files.reduce((acc, snapshotFile) => {
if (!fileExists(snapshotResolver.resolveTestPath(snapshotFile), hasteFS)) {
if (update === 'all') {
fs.unlinkSync(snapshotFile);
}
return acc + 1;
}
return acc;
}, 0);
return {
filesRemoved,
};
};
const toMatchSnapshot = function(
this: Context,
received: any,
propertyMatchers?: any,
testName?: Config.Path,
) {
if (arguments.length === 3 && !propertyMatchers) {
throw new Error(
'Property matchers must be an object.\n\nTo provide a snapshot test name without property matchers, use: toMatchSnapshot("name")',
);
}
return _toMatchSnapshot({
context: this,
propertyMatchers,
received,
testName,
});
};
const toMatchInlineSnapshot = function(
this: Context,
received: any,
propertyMatchersOrInlineSnapshot?: any,
inlineSnapshot?: string,
) {
let propertyMatchers;
if (typeof propertyMatchersOrInlineSnapshot === 'string') {
inlineSnapshot = propertyMatchersOrInlineSnapshot;
} else {
propertyMatchers = propertyMatchersOrInlineSnapshot;
}
return _toMatchSnapshot({
context: this,
inlineSnapshot: inlineSnapshot || '',
propertyMatchers,
received,
});
};
const _toMatchSnapshot = ({
context,
received,
propertyMatchers,
testName,
inlineSnapshot,
}: {
context: Context;
received: any;
propertyMatchers?: any;
testName?: string;
inlineSnapshot?: string;
}) => {
context.dontThrow && context.dontThrow();
testName = typeof propertyMatchers === 'string' ? propertyMatchers : testName;
const {currentTestName, isNot, snapshotState} = context;
if (isNot) {
const matcherName =
typeof inlineSnapshot === 'string'
? 'toMatchInlineSnapshot'
: 'toMatchSnapshot';
throw new Error(
`Jest: \`.not\` cannot be used with \`.${matcherName}()\`.`,
);
}
if (!snapshotState) {
throw new Error('Jest: snapshot state must be initialized.');
}
const fullTestName =
testName && currentTestName
? `${currentTestName}: ${testName}`
: currentTestName || '';
if (typeof propertyMatchers === 'object') {
if (propertyMatchers === null) {
throw new Error(`Property matchers must be an object.`);
}
const propertyPass = context.equals(received, propertyMatchers, [
context.utils.iterableEquality,
context.utils.subsetEquality,
]);
if (!propertyPass) {
const key = snapshotState.fail(fullTestName, received);
const report = () =>
`${RECEIVED_COLOR('Received value')} does not match ` +
`${EXPECTED_COLOR(`snapshot properties for "${key}"`)}.\n\n` +
`Expected snapshot to match properties:\n` +
` ${context.utils.printExpected(propertyMatchers)}` +
`\nReceived:\n` +
` ${context.utils.printReceived(received)}`;
return {
message: () =>
matcherHint('.toMatchSnapshot', 'value', 'properties') +
'\n\n' +
report(),
name: 'toMatchSnapshot',
pass: false,
report,
};
} else {
received = utils.deepMerge(received, propertyMatchers);
}
}
const result = snapshotState.match({
error: context.error,
inlineSnapshot,
received,
testName: fullTestName,
});
const {pass} = result;
let {actual, expected} = result;
let report: () => string;
if (pass) {
return {message: () => '', pass: true};
} else if (!expected) {
report = () =>
`New snapshot was ${RECEIVED_COLOR('not written')}. The update flag ` +
`must be explicitly passed to write a new snapshot.\n\n` +
`This is likely because this test is run in a continuous integration ` +
`(CI) environment in which snapshots are not written by default.\n\n` +
`${RECEIVED_COLOR('Received value')} ` +
`${actual}`;
} else {
expected = (expected || '').trim();
actual = (actual || '').trim();
const diffMessage = diff(expected, actual, {
aAnnotation: 'Snapshot',
bAnnotation: 'Received',
expand: snapshotState.expand,
});
report = () =>
`${RECEIVED_COLOR('Received value')} does not match ` +
`${EXPECTED_COLOR(`stored snapshot "${result.key}"`)}.\n\n` +
(diffMessage ||
EXPECTED_COLOR('- ' + (expected || '')) +
'\n' +
RECEIVED_COLOR('+ ' + actual));
}
// Passing the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual,
expected,
message: () =>
matcherHint('.toMatchSnapshot', 'value', '') + '\n\n' + report(),
name: 'toMatchSnapshot',
pass: false,
report,
};
};
const toThrowErrorMatchingSnapshot = function(
this: Context,
received: any,
testName: string | undefined,
fromPromise: boolean,
) {
return _toThrowErrorMatchingSnapshot({
context: this,
fromPromise,
received,
testName,
});
};
const toThrowErrorMatchingInlineSnapshot = function(
this: Context,
received: any,
inlineSnapshot?: string,
fromPromise?: boolean,
) {
return _toThrowErrorMatchingSnapshot({
context: this,
fromPromise,
inlineSnapshot: inlineSnapshot || '',
received,
});
};
const _toThrowErrorMatchingSnapshot = ({
context,
received,
testName,
fromPromise,
inlineSnapshot,
}: {
context: Context;
received: any;
testName?: string;
fromPromise?: boolean;
inlineSnapshot?: string;
}) => {
context.dontThrow && context.dontThrow();
const {isNot} = context;
const matcherName =
typeof inlineSnapshot === 'string'
? 'toThrowErrorMatchingInlineSnapshot'
: 'toThrowErrorMatchingSnapshot';
if (isNot) {
throw new Error(
`Jest: \`.not\` cannot be used with \`.${matcherName}()\`.`,
);
}
let error;
if (fromPromise) {
error = received;
} else {
try {
received();
} catch (e) {
error = e;
}
}
if (error === undefined) {
throw new Error(
matcherHint(`.${matcherName}`, '() => {}', '') +
'\n\n' +
`Expected the function to throw an error.\n` +
`But it didn't throw anything.`,
);
}
return _toMatchSnapshot({
context,
inlineSnapshot,
received: error.message,
testName,
});
};
export = {
EXTENSION,
SnapshotState,
addSerializer,
buildSnapshotResolver,
cleanup,
getSerializers,
isSnapshotPath,
toMatchInlineSnapshot,
toMatchSnapshot,
toThrowErrorMatchingInlineSnapshot,
toThrowErrorMatchingSnapshot,
utils,
};