-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Utils.ts
262 lines (231 loc) · 6.89 KB
/
Utils.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
/**
* 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 * as path from 'path';
import type {Config} from '@jest/types';
// eslint-disable-next-line import/named
import {ExecaReturnValue, sync as spawnSync} from 'execa';
import makeDir = require('make-dir');
import rimraf = require('rimraf');
import dedent = require('dedent');
interface RunResult extends ExecaReturnValue {
status: number;
error: Error;
}
export const run = (cmd: string, cwd?: Config.Path): RunResult => {
const args = cmd.split(/\s/).slice(1);
const spawnOptions = {cwd, preferLocal: false, reject: false};
const result = spawnSync(cmd.split(/\s/)[0], args, spawnOptions) as RunResult;
// For compat with cross-spawn
result.status = result.exitCode;
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: Config.Path) => {
const packagesDir = path.resolve(__dirname, '../packages');
const packagePath = path.resolve(packagesDir, packageName);
const destination = path.resolve(cwd, 'node_modules/', packageName);
makeDir.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},
) => {
makeDir.sync(directory);
Object.keys(files).forEach(fileOrPath => {
const dirname = path.dirname(fileOrPath);
if (dirname !== '/') {
makeDir.sync(path.join(directory, dirname));
}
fs.writeFileSync(
path.resolve(directory, ...fileOrPath.split('/')),
dedent(files[fileOrPath]),
);
});
};
export const writeSymlinks = (
directory: string,
symlinks: {[existingFile: string]: string},
) => {
makeDir.sync(directory);
Object.keys(symlinks).forEach(fileOrPath => {
const symLinkPath = symlinks[fileOrPath];
const dirname = path.dirname(symLinkPath);
if (dirname !== '/') {
makeDir.sync(path.join(directory, dirname));
}
fs.symlinkSync(
path.resolve(directory, ...fileOrPath.split('/')),
path.resolve(directory, ...symLinkPath.split('/')),
);
});
};
const NUMBER_OF_TESTS_TO_FORCE_USING_WORKERS = 25;
/**
* Forces Jest to use workers by generating many test files to run.
* Slow and modifies the test output. Use sparingly.
*/
export const generateTestFilesToForceUsingWorkers = () => {
const testFiles: Record<string, string> = {};
for (let i = 0; i <= NUMBER_OF_TESTS_TO_FORCE_USING_WORKERS; i++) {
testFiles[`__tests__/test${i}.test.js`] = `
test.todo('test ${i}');
`;
}
return testFiles;
};
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\b/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: Config.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',
},
};
makeDir.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
.replace(/(?:\\[rn])+/g, '\n')
.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 = stdout
.replace(match[0], '')
// remove all timestamps
.replace(/\s*\(\d*\.?\d+ m?s\b\)$/gm, '');
return {
rest: rest.trim(),
summary: summary.trim(),
};
};
const sortTests = (stdout: string) =>
stdout
.split('\n')
.reduce((tests: Array<Array<string>>, line) => {
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: Array<RegExpExecArray> = [];
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)));
};
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');
};