forked from jestjs/jest
/
inline_snapshots.js
192 lines (170 loc) · 5.68 KB
/
inline_snapshots.js
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
/**
* 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.
*
* @flow
*/
import fs from 'fs';
import semver from 'semver';
import path from 'path';
import {templateElement, templateLiteral, file} from '@babel/types';
import type {Path} from 'types/Config';
import {escapeBacktickString} from './utils';
export type InlineSnapshot = {|
snapshot: string,
frame: {line: number, column: number, file: string},
sliceStart ?: number,
sliceEnd ?: number,
shouldHaveCommaPrefix ?: boolean,
|};
export const saveInlineSnapshots = (
snapshots: InlineSnapshot[],
prettier: any,
babelTraverse: Function,
) => {
if (!prettier) {
throw new Error(
`Jest: Inline Snapshots requires Prettier.\n` +
`Please ensure "prettier" is installed in your project.`,
);
}
// Custom parser API was added in 1.5.0
if (semver.lt(prettier.version, '1.5.0')) {
throw new Error(
`Jest: Inline Snapshots require prettier>=1.5.0.\n` +
`Please upgrade "prettier".`,
);
}
const snapshotsByFile = groupSnapshotsByFile(snapshots);
for (const sourceFilePath of Object.keys(snapshotsByFile)) {
saveSnapshotsForFile(
snapshotsByFile[sourceFilePath],
sourceFilePath,
prettier,
babelTraverse,
);
}
};
const saveSnapshotsForFile = (
snapshots: Array<InlineSnapshot>,
sourceFilePath: Path,
prettier: any,
babelTraverse: Function,
) => {
const sourceFile = fs.readFileSync(sourceFilePath, 'utf8');
// Resolve project configuration.
// For older versions of Prettier, do not load configuration.
const config = prettier.resolveConfig
? prettier.resolveConfig.sync(sourceFilePath, {
editorconfig: true,
})
: null;
// Detect the parser for the test file.
// For older versions of Prettier, fallback to a simple parser detection.
const inferredParser = prettier.getFileInfo
? prettier.getFileInfo.sync(sourceFilePath).inferredParser
: (config && config.parser) || simpleDetectParser(sourceFilePath);
// Format the source code using the custom parser API.
// The output isn't used, but prettier provides an ast
// which is used to calculate snapshot offsets.
prettier.format(sourceFile, {
...config,
filepath: sourceFilePath,
parser: createParser(snapshots, inferredParser, babelTraverse),
});
// substitute in the snapshots in reverse order, so the slice calculations aren't thrown off.
const newSourceFile = snapshots.reduceRight(
(sourceSoFar, nextSnapshot) =>
sourceSoFar.slice(0, nextSnapshot.sliceStart) +
(nextSnapshot.shouldHaveCommaPrefix ? ', `' : '`') +
escapeBacktickString(nextSnapshot.snapshot) +
'`' +
sourceSoFar.slice(nextSnapshot.sliceEnd),
sourceFile
);
if (newSourceFile !== sourceFile) {
fs.writeFileSync(sourceFilePath, newSourceFile);
}
};
const groupSnapshotsBy = (createKey: InlineSnapshot => string) => (
snapshots: Array<InlineSnapshot>,
) =>
snapshots.reduce((object, inlineSnapshot) => {
const key = createKey(inlineSnapshot);
return {...object, [key]: (object[key] || []).concat(inlineSnapshot)};
}, {});
const groupSnapshotsByFrame = groupSnapshotsBy(
({frame: {line, column}}) => `${line}:${column - 1}`,
);
const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file);
const createParser = (
snapshots: InlineSnapshot[],
inferredParser: string,
babelTraverse: Function,
) => (
text: string,
parsers: {[key: string]: (string) => any},
options: any,
) => {
// Workaround for https://github.com/prettier/prettier/issues/3150
options.parser = inferredParser;
const groupedSnapshots = groupSnapshotsByFrame(snapshots);
const remainingSnapshots = new Set(snapshots.map(({snapshot}) => snapshot));
let ast = parsers[inferredParser](text);
// Flow uses a 'Program' parent node, babel expects a 'File'.
if (ast.type !== 'File') {
ast = file(ast, ast.comments, ast.tokens);
delete ast.program.comments;
}
babelTraverse(ast, {
CallExpression({node: {arguments: args, callee}}) {
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier'
) {
return;
}
const {line, column} = callee.property.loc.start;
const snapshotsForFrame = groupedSnapshots[`${line}:${column}`];
if (!snapshotsForFrame) {
return;
}
if (snapshotsForFrame.length > 1) {
throw new Error(
'Jest: Multiple inline snapshots for the same call are not supported.',
);
}
const snapshotIndex = args.findIndex(
({type}) => type === 'TemplateLiteral',
);
snapshotsForFrame.forEach(inlineSnapshot => {
const { snapshot } = inlineSnapshot
if (snapshotIndex > -1) {
inlineSnapshot.sliceStart = args[snapshotIndex].start;
inlineSnapshot.sliceEnd = args[snapshotIndex].end;
} else if (args.length > 0) {
inlineSnapshot.shouldHaveCommaPrefix = true;
inlineSnapshot.sliceStart = args[args.length - 1].end;
inlineSnapshot.sliceEnd = inlineSnapshot.sliceStart;
} else {
inlineSnapshot.sliceStart = text.indexOf('(', callee.end) + 1;
inlineSnapshot.sliceEnd = inlineSnapshot.sliceStart;
}
remainingSnapshots.delete(snapshot);
})
},
});
if (remainingSnapshots.size) {
throw new Error(`Jest: Couldn't locate all inline snapshots.`);
}
return ast;
};
const simpleDetectParser = (filePath: Path) => {
const extname = path.extname(filePath);
if (/tsx?$/.test(extname)) {
return 'typescript';
}
return 'babylon';
};