-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathindex.ts
529 lines (470 loc) · 13.1 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/**
* 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 * as fs from 'fs';
import {Config} from '@jest/types';
import {FS as HasteFS} from 'jest-haste-map'; // eslint-disable-line import/no-extraneous-dependencies
import {MatcherState} from 'expect';
import {
BOLD_WEIGHT,
MatcherHintOptions,
RECEIVED_COLOR,
matcherHint,
} from 'jest-matcher-utils';
import {
EXTENSION,
SnapshotResolver as JestSnapshotResolver,
buildSnapshotResolver,
isSnapshotPath,
} from './snapshot_resolver';
import SnapshotState from './State';
import {addSerializer, getSerializers} from './plugins';
import {printDiffOrStringified} from './print';
import * as utils from './utils';
type Context = MatcherState & {
snapshotState: SnapshotState;
};
type MatchSnapshotConfig = {
context: Context;
expectedArgument: string;
hint?: string;
inlineSnapshot?: string;
isInline: boolean;
matcherName: string;
options: MatcherHintOptions;
propertyMatchers?: any;
received: any;
};
const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow
const NOT_SNAPSHOT_MATCHERS = `.${BOLD_WEIGHT(
'not',
)} cannot be used with snapshot matchers`;
const HINT_ARG = 'hint';
const HINT_COLOR = BOLD_WEIGHT;
const INLINE_SNAPSHOT_ARG = 'snapshot';
const PROPERTY_MATCHERS_ARG = 'properties';
const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
// Display name in report when matcher fails same as in snapshot file,
// but with optional hint argument in bold weight.
const printName = (
concatenatedBlockNames = '',
hint = '',
count: number,
): string => {
const hasNames = concatenatedBlockNames.length !== 0;
const hasHint = hint.length !== 0;
return (
'`' +
(hasNames ? utils.escapeBacktickString(concatenatedBlockNames) : '') +
(hasNames && hasHint ? ': ' : '') +
(hasHint ? BOLD_WEIGHT(utils.escapeBacktickString(hint)) : '') +
' ' +
count +
'`'
);
};
function stripAddedIndentation(inlineSnapshot: string) {
// Find indentation if exists.
const match = inlineSnapshot.match(INDENTATION_REGEX);
if (!match || !match[1]) {
// No indentation.
return inlineSnapshot;
}
const indentation = match[1];
const lines = inlineSnapshot.split('\n');
if (lines.length <= 2) {
// Must be at least 3 lines.
return inlineSnapshot;
}
if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') {
// If not blank first and last lines, abort.
return inlineSnapshot;
}
for (let i = 1; i < lines.length - 1; i++) {
if (lines[i] !== '') {
if (lines[i].indexOf(indentation) !== 0) {
// All lines except first and last should either be blank or have the same
// indent as the first line (or more). If this isn't the case we don't
// want to touch the snapshot at all.
return inlineSnapshot;
}
lines[i] = lines[i].substr(indentation.length);
}
}
// Last line is a special case because it won't have the same indent as others
// but may still have been given some indent to line up.
lines[lines.length - 1] = '';
// Return inline snapshot, now at indent 0.
inlineSnapshot = lines.join('\n');
return inlineSnapshot;
}
const fileExists = (filePath: Config.Path, hasteFS: HasteFS): boolean =>
hasteFS.exists(filePath) || fs.existsSync(filePath);
const cleanup = (
hasteFS: HasteFS,
update: Config.SnapshotUpdateState,
snapshotResolver: JestSnapshotResolver,
testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'],
): {
filesRemoved: number;
filesRemovedList: Array<string>;
} => {
const pattern = '\\.' + EXTENSION + '$';
const files = hasteFS.matchFiles(pattern);
let testIgnorePatternsRegex: RegExp | null = null;
if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {
testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));
}
const list = files.filter(snapshotFile => {
const testPath = snapshotResolver.resolveTestPath(snapshotFile);
// ignore snapshots of ignored tests
if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {
return false;
}
if (!fileExists(testPath, hasteFS)) {
if (update === 'all') {
fs.unlinkSync(snapshotFile);
}
return true;
}
return false;
});
return {
filesRemoved: list.length,
filesRemovedList: list,
};
};
const toMatchSnapshot = function(
this: Context,
received: any,
propertyMatchers?: any,
hint?: Config.Path,
) {
const matcherName = 'toMatchSnapshot';
let expectedArgument = '';
let secondArgument = '';
if (typeof propertyMatchers === 'object' && propertyMatchers !== null) {
expectedArgument = PROPERTY_MATCHERS_ARG;
if (typeof hint === 'string' && hint.length !== 0) {
secondArgument = HINT_ARG;
}
} else if (
typeof propertyMatchers === 'string' &&
propertyMatchers.length !== 0
) {
expectedArgument = HINT_ARG;
}
const options: MatcherHintOptions = {
isNot: this.isNot,
promise: this.promise,
secondArgument,
};
if (expectedArgument === HINT_ARG) {
options.expectedColor = HINT_COLOR;
}
if (secondArgument === HINT_ARG) {
options.secondArgumentColor = HINT_COLOR;
}
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,
expectedArgument,
hint,
isInline: false,
matcherName,
options,
propertyMatchers,
received,
});
};
const toMatchInlineSnapshot = function(
this: Context,
received: any,
propertyMatchersOrInlineSnapshot?: any,
inlineSnapshot?: string,
) {
const matcherName = 'toMatchInlineSnapshot';
let expectedArgument = '';
let secondArgument = '';
if (typeof propertyMatchersOrInlineSnapshot === 'string') {
expectedArgument = INLINE_SNAPSHOT_ARG;
} else if (
typeof propertyMatchersOrInlineSnapshot === 'object' &&
propertyMatchersOrInlineSnapshot !== null
) {
expectedArgument = PROPERTY_MATCHERS_ARG;
if (typeof inlineSnapshot === 'string') {
secondArgument = INLINE_SNAPSHOT_ARG;
}
}
const options: MatcherHintOptions = {
isNot: this.isNot,
promise: this.promise,
secondArgument,
};
let propertyMatchers;
if (typeof propertyMatchersOrInlineSnapshot === 'string') {
inlineSnapshot = propertyMatchersOrInlineSnapshot;
} else {
propertyMatchers = propertyMatchersOrInlineSnapshot;
}
return _toMatchSnapshot({
context: this,
expectedArgument,
inlineSnapshot:
inlineSnapshot !== undefined
? stripAddedIndentation(inlineSnapshot)
: undefined,
isInline: true,
matcherName,
options,
propertyMatchers,
received,
});
};
const _toMatchSnapshot = ({
context,
expectedArgument,
hint,
inlineSnapshot,
isInline,
matcherName,
options,
propertyMatchers,
received,
}: MatchSnapshotConfig) => {
context.dontThrow && context.dontThrow();
hint = typeof propertyMatchers === 'string' ? propertyMatchers : hint;
const {currentTestName, isNot, snapshotState} = context;
if (isNot) {
throw new Error(
matcherHint(matcherName, undefined, expectedArgument, options) +
'\n\n' +
NOT_SNAPSHOT_MATCHERS,
);
}
if (!snapshotState) {
throw new Error(
matcherHint(matcherName, undefined, expectedArgument, options) +
'\n\nsnapshot state must be initialized',
);
}
const fullTestName =
currentTestName && hint
? `${currentTestName}: ${hint}`
: currentTestName || ''; // future BREAKING change: || hint
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 matched = /(\d+)$/.exec(key);
const count = matched === null ? 1 : Number(matched[1]);
const report = () =>
`Snapshot name: ${printName(currentTestName, hint, count)}\n` +
'\n' +
`Expected properties: ${context.utils.printExpected(
propertyMatchers,
)}\n` +
`Received value: ${context.utils.printReceived(received)}`;
return {
message: () =>
matcherHint(matcherName, undefined, expectedArgument, options) +
'\n\n' +
report(),
name: matcherName,
pass: false,
report,
};
} else {
received = utils.deepMerge(received, propertyMatchers);
}
}
const result = snapshotState.match({
error: context.error,
inlineSnapshot,
isInline,
received,
testName: fullTestName,
});
const {count, pass} = result;
let {actual, expected} = result;
let report: () => string;
if (pass) {
return {message: () => '', pass: true};
} else if (expected === undefined) {
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 = utils.removeExtraLineBreaks(expected);
actual = utils.removeExtraLineBreaks(actual);
// Assign to local variable because of declaration let expected:
// TypeScript thinks it could change before report function is called.
const printed = printDiffOrStringified(
expected,
actual,
received,
'Snapshot',
'Received',
snapshotState.expand,
);
report = () =>
`Snapshot name: ${printName(currentTestName, hint, count)}\n\n` + printed;
}
// 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(matcherName, undefined, expectedArgument, options) +
'\n\n' +
report(),
name: matcherName,
pass: false,
report,
};
};
const toThrowErrorMatchingSnapshot = function(
this: Context,
received: any,
hint: string | undefined, // because error TS1016 for hint?: string
fromPromise: boolean,
) {
const matcherName = 'toThrowErrorMatchingSnapshot';
const expectedArgument =
typeof hint === 'string' && hint.length !== 0 ? HINT_ARG : '';
const options = {
expectedColor: HINT_COLOR,
isNot: this.isNot,
promise: this.promise,
secondArgument: '',
};
return _toThrowErrorMatchingSnapshot(
{
context: this,
expectedArgument,
hint,
isInline: false,
matcherName,
options,
received,
},
fromPromise,
);
};
const toThrowErrorMatchingInlineSnapshot = function(
this: Context,
received: any,
inlineSnapshot?: string,
fromPromise?: boolean,
) {
const matcherName = 'toThrowErrorMatchingInlineSnapshot';
const expectedArgument =
typeof inlineSnapshot === 'string' ? INLINE_SNAPSHOT_ARG : '';
const options: MatcherHintOptions = {
isNot: this.isNot,
promise: this.promise,
secondArgument: '',
};
return _toThrowErrorMatchingSnapshot(
{
context: this,
expectedArgument,
inlineSnapshot,
isInline: true,
matcherName,
options,
received,
},
fromPromise,
);
};
const _toThrowErrorMatchingSnapshot = (
{
context,
expectedArgument,
inlineSnapshot,
isInline,
matcherName,
options,
received,
hint,
}: MatchSnapshotConfig,
fromPromise?: boolean,
) => {
context.dontThrow && context.dontThrow();
const {isNot} = context;
if (isNot) {
throw new Error(
matcherHint(matcherName, undefined, expectedArgument, options) +
'\n\n' +
NOT_SNAPSHOT_MATCHERS,
);
}
let error;
if (fromPromise) {
error = received;
} else {
try {
received();
} catch (e) {
error = e;
}
}
if (error === undefined) {
throw new Error(
matcherHint(matcherName, undefined, expectedArgument, options) +
'\n\n' +
DID_NOT_THROW,
);
}
return _toMatchSnapshot({
context,
expectedArgument,
hint,
inlineSnapshot,
isInline,
matcherName,
options,
received: error.message,
});
};
const JestSnapshot = {
EXTENSION,
SnapshotState,
addSerializer,
buildSnapshotResolver,
cleanup,
getSerializers,
isSnapshotPath,
toMatchInlineSnapshot,
toMatchSnapshot,
toThrowErrorMatchingInlineSnapshot,
toThrowErrorMatchingSnapshot,
utils,
};
/* eslint-disable-next-line no-redeclare */
namespace JestSnapshot {
export type SnapshotResolver = JestSnapshotResolver;
export type SnapshotStateType = SnapshotState;
}
export = JestSnapshot;