-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Utils.js
230 lines (200 loc) · 6.04 KB
/
Utils.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
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
/**
* Copyright (c) 2014-present, Facebook, Inc. 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
*/
'use strict';
import type {Path} from 'types/Config';
import {sync as spawnSync} from 'execa';
import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
export const run = (cmd: string, cwd?: Path) => {
const args = cmd.split(/\s/).slice(1);
const spawnOptions = {cwd, reject: false};
const result = spawnSync(cmd.split(/\s/)[0], args, spawnOptions);
// For compat with cross-spawn
result.status = result.code;
if (result.status !== 0) {
const message = `
ORIGINAL CMD: ${cmd}
STDOUT: ${result.stdout}
STDERR: ${result.stderr}
STATUS: ${result.status}
ERROR: ${result.error}
`;
throw new Error(message);
}
return result;
};
export const linkJestPackage = (packageName: string, cwd: Path) => {
const packagesDir = path.resolve(__dirname, '../packages');
const packagePath = path.resolve(packagesDir, packageName);
const destination = path.resolve(cwd, 'node_modules/', packageName);
mkdirp.sync(destination);
rimraf.sync(destination);
fs.symlinkSync(packagePath, destination, 'dir');
};
export const makeTemplate = (
str: string,
): ((values?: Array<any>) => string) => (values: ?Array<any>) =>
str.replace(/\$(\d+)/g, (match, number) => {
if (!Array.isArray(values)) {
throw new Error('Array of values must be passed to the template.');
}
return values[number - 1];
});
export const cleanup = (directory: string) => rimraf.sync(directory);
/**
* Creates a nested directory with files and their contents
* writeFiles(
* '/home/tmp',
* {
* 'package.json': '{}',
* '__tests__/test.test.js': 'test("lol")',
* }
* );
*/
export const writeFiles = (
directory: string,
files: {[filename: string]: string},
) => {
mkdirp.sync(directory);
Object.keys(files).forEach(fileOrPath => {
const filePath = fileOrPath.split('/'); // ['tmp', 'a.js']
const filename = filePath.pop(); // filepath becomes dirPath (no filename)
if (filePath.length) {
mkdirp.sync(path.join.apply(path, [directory].concat(filePath)));
}
fs.writeFileSync(
path.resolve.apply(path, [directory].concat(filePath, [filename])),
files[fileOrPath],
);
});
};
export const copyDir = (src: string, dest: string) => {
const srcStat = fs.lstatSync(src);
if (srcStat.isDirectory()) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).map(filePath =>
copyDir(path.join(src, filePath), path.join(dest, filePath)),
);
} else {
fs.writeFileSync(dest, fs.readFileSync(src));
}
};
export const replaceTime = (str: string) =>
str
.replace(/\d*\.?\d+m?s/g, '<<REPLACED>>')
.replace(/, estimated <<REPLACED>>/g, '');
// Since Jest does not guarantee the order of tests we'll sort the output.
export const sortLines = (output: string) =>
output
.split('\n')
.sort()
.map(str => str.trim())
.filter(Boolean)
.join('\n');
export const createEmptyPackage = (
directory: Path,
packageJson?: {[keys: string]: any},
) => {
const DEFAULT_PACKAGE_JSON = {
description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT',
jest: {
testEnvironment: 'node',
},
};
mkdirp.sync(directory);
packageJson || (packageJson = DEFAULT_PACKAGE_JSON);
fs.writeFileSync(
path.resolve(directory, 'package.json'),
JSON.stringify(packageJson, null, 2),
);
};
export const extractSummary = (stdout: string) => {
const match = stdout.match(
/Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm,
);
if (!match) {
throw new Error(
`
Could not find test summary in the output.
OUTPUT:
${stdout}
`,
);
}
const summary = replaceTime(match[0]);
const rest = cleanupStackTrace(
// remove all timestamps
stdout.replace(match[0], '').replace(/\s*\(\d*\.?\d+m?s\)$/gm, ''),
);
return {rest, summary};
};
const sortTests = (stdout: string) =>
stdout
.split('\n')
.reduce((tests, line, i) => {
if (['RUNS', 'PASS', 'FAIL'].includes(line.slice(0, 4))) {
tests.push([line.trimRight()]);
} else if (line) {
tests[tests.length - 1].push(line.trimRight());
}
return tests;
}, [])
.sort(([a], [b]) => (a > b ? 1 : -1))
.reduce(
(array, lines = []) =>
lines.length > 1 ? array.concat(lines, '') : array.concat(lines),
[],
)
.join('\n');
export const extractSortedSummary = (stdout: string) => {
const {rest, summary} = extractSummary(stdout);
return {
rest: sortTests(replaceTime(rest)),
summary,
};
};
export const extractSummaries = (
stdout: string,
): Array<{rest: string, summary: string}> => {
const regex = /Test Suites:.*\nTests.*\nSnapshots.*\nTime.*(\nRan all test suites)*.*\n*$/gm;
let match = regex.exec(stdout);
const matches = [];
while (match) {
matches.push(match);
match = regex.exec(stdout);
}
return matches
.map((currentMatch, i) => {
const prevMatch = matches[i - 1];
const start = prevMatch ? prevMatch.index + prevMatch[0].length : 0;
const end = currentMatch.index + currentMatch[0].length;
return {end, start};
})
.map(({start, end}) => extractSortedSummary(stdout.slice(start, end)));
};
// different versions of Node print different stack traces. This function
// unifies their output to make it possible to snapshot them.
// TODO: Remove when we drop support for node 4
export const cleanupStackTrace = (output: string) =>
output
.replace(/.*(?=packages)/g, ' at ')
.replace(/^.*at.*[\s][\(]?(\S*\:\d*\:\d*).*$/gm, ' at $1');
export const normalizeIcons = (str: string) => {
if (!str) {
return str;
}
// Make sure to keep in sync with `jest-cli/src/constants`
return str
.replace(new RegExp('\u00D7', 'g'), '\u2715')
.replace(new RegExp('\u221A', 'g'), '\u2713');
};