/
worker-runner.js
313 lines (275 loc) · 8.36 KB
/
worker-runner.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
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
import path from "path";
import { fileURLToPath, pathToFileURL } from "url";
import { performance } from "perf_hooks";
import * as snapshot from "jest-snapshot";
import { expect } from "expect";
import * as circus from "jest-circus";
import { inspect } from "util";
import { isWorkerThread } from "piscina";
/** @typedef {{ failures: number, passes: number, pending: number, start: number, end: number }} Stats */
/** @typedef {{ ancestors: string[], title: string, duration: number, errors: Error[], skipped: boolean }} InternalTestResult */
const initialSetup = once(async projectConfig => {
// Node.js workers (worker_threads) don't support
// process.chdir, that we use multiple times in our tests.
// We can "polyfill" it for process.cwd() usage, but it
// won't affect path.* and fs.* functions.
if (isWorkerThread) {
const startCwd = process.cwd();
let cwd = startCwd;
process.cwd = () => cwd;
process.chdir = dir => {
cwd = path.resolve(cwd, dir);
};
}
for (const setupFile of projectConfig.setupFiles) {
const { default: setup } = await import(pathToFileURL(setupFile));
// https://github.com/facebook/jest/issues/11038
if (typeof setup === "function") await setup();
}
await import("./global-setup.js");
for (const snapshotSerializer of projectConfig.snapshotSerializers
.slice()
.reverse()) {
const { default: serializer } = await import(
pathToFileURL(snapshotSerializer)
);
snapshot.addSerializer(serializer);
}
for (const setupFile of projectConfig.setupFilesAfterEnv) {
const { default: setup } = await import(pathToFileURL(setupFile));
if (typeof setup === "function") await setup();
}
return snapshot.getSerializers().slice();
});
export default async function run({
test,
updateSnapshot,
testNamePattern,
port,
}) {
const projectSnapshotSerializers = await initialSetup(test.context.config);
port.postMessage("start");
const testNamePatternRE =
testNamePattern != null ? new RegExp(testNamePattern, "i") : null;
/** @type {Stats} */
const stats = { passes: 0, failures: 0, pending: 0, start: 0, end: 0 };
/** @type {Array<InternalTestResult>} */
const results = [];
const { tests, hasFocusedTests } = await loadTests(test.path);
const snapshotResolver = await snapshot.buildSnapshotResolver(
test.context.config
);
const snapshotState = new snapshot.SnapshotState(
snapshotResolver.resolveSnapshotPath(test.path),
{
prettierPath: "prettier",
updateSnapshot,
snapshotFormat: test.context.config.snapshotFormat,
}
);
expect.setState({ snapshotState, testPath: test.path });
stats.start = performance.now();
await runTestBlock(tests, hasFocusedTests, testNamePatternRE, results, stats);
stats.end = performance.now();
snapshotState.save();
// Restore the project-level serializers, so that serializers
// installed by one test file don't leak to other files.
arrayReplace(snapshot.getSerializers(), projectSnapshotSerializers);
return toTestResult(stats, results, test);
}
async function loadTests(testFile) {
circus.resetState();
await import(pathToFileURL(testFile) + "?" + Date.now());
const { rootDescribeBlock, hasFocusedTests } = circus.getState();
return { tests: rootDescribeBlock, hasFocusedTests };
}
async function runTestBlock(
block,
hasFocusedTests,
testNamePatternRE,
results,
stats,
ancestors = []
) {
await runHooks("beforeAll", block, results, stats, ancestors);
for (const child of block.children) {
const { type, mode, fn, name } = child;
const nextAncestors = ancestors.concat(name);
if (
mode === "skip" ||
(type === "test" &&
((hasFocusedTests && mode !== "only") ||
shouldSkip(testNamePatternRE, getFullName(nextAncestors))))
) {
stats.pending++;
results.push({ ancestors, title: name, errors: [], skipped: true });
} else if (type === "describeBlock") {
await runTestBlock(
child,
hasFocusedTests,
testNamePatternRE,
results,
stats,
nextAncestors
);
} else if (type === "test") {
await runHooks("beforeEach", block, results, stats, nextAncestors, true);
await runTest(fn, stats, results, ancestors, name);
await runHooks("afterEach", block, results, stats, nextAncestors, true);
}
}
await runHooks("afterAll", block, results, stats, ancestors);
return results;
}
function shouldSkip(testNamePatternRE, testName) {
return testNamePatternRE && !testNamePatternRE.test(testName);
}
/**
* @param {string[]} pieces
*/
function getFullName(pieces) {
return pieces.join(" ");
}
/**
* @param {Function} fn
* @param {Stats} stats
* @param {Array<InternalTestResult>} results
* @param {string[]} ancestors
* @param {string} name
*/
async function runTest(fn, stats, results, ancestors, name) {
expect.setState({
suppressedErrors: [],
currentTestName: getFullName(ancestors.concat(name)),
});
const errors = [];
await callAsync(fn).catch(error => {
errors.push(error);
});
// Get suppressed errors from ``jest-matchers`` that weren't thrown during
// test execution and add them to the test result, potentially failing
// a passing test.
const { suppressedErrors } = expect.getState();
expect.setState({ suppressedErrors: [] });
if (suppressedErrors.length > 0) {
errors.unshift(...suppressedErrors);
}
if (errors.length > 0) {
stats.failures++;
} else {
stats.passes++;
}
results.push({ ancestors, title: name, errors, skipped: false });
}
async function runHooks(hook, block, results, stats, ancestors, runInParents) {
if (hook.startsWith("before") && block.parent && runInParents) {
await runHooks(hook, block.parent, results, stats, ancestors, true);
}
for (const { type, fn } of block.hooks) {
if (type === hook) {
await callAsync(fn).catch(error => {
stats.failures++;
results.push({
ancestors,
title: `(${hook})`,
errors: [error],
skipped: false,
});
});
}
}
if (hook.startsWith("after") && block.parent && runInParents) {
await runHooks(hook, block.parent, results, stats, ancestors, true);
}
}
function callAsync(fn) {
if (fn.length >= 1) {
return new Promise((resolve, reject) => {
fn((err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
} else {
return Promise.resolve().then(fn);
}
}
/**
*
* @param {Stats} stats
* @param {Array<InternalTestResult>} tests
* @param {import("@jest/test-result").Test} testInput
* @returns {import("@jest/test-result").TestResult}
*/
function toTestResult(stats, tests, { path, context }) {
const { start, end } = stats;
const runtime = end - start;
return {
coverage: globalThis.__coverage__,
console: null,
failureMessage: tests
.filter(t => t.errors.length > 0)
.map(failureToString)
.join("\n"),
numFailingTests: stats.failures,
numPassingTests: stats.passes,
numPendingTests: stats.pending,
perfStats: {
start,
end,
runtime: Math.round(runtime), // ms precision
slow: runtime / 1000 > context.config.slowTestThreshold,
},
skipped: false,
snapshot: {
added: 0,
fileDeleted: false,
matched: 0,
unchecked: 0,
unmatched: 0,
updated: 0,
},
sourceMaps: {},
testExecError: null,
testFilePath: path,
testResults: tests.map(test => {
return {
ancestorTitles: test.ancestors,
duration: test.duration / 1000,
failureMessages: test.errors.length ? [failureToString(test)] : [],
fullName: test.title,
numPassingAsserts: test.errors.length > 0 ? 1 : 0,
status: test.skipped
? "pending"
: test.errors.length > 0
? "failed"
: "passed",
title: test.title,
};
}),
};
}
function failureToString(test) {
return (
test.ancestors.concat(test.title).join(" > ") +
"\n" +
test.errors.map(error => inspect(error).replace(/^/gm, " ")).join("\n") +
"\n"
);
}
function once(fn) {
let called = false;
let result;
return function () {
if (called) return result;
called = true;
result = fn.apply(this, arguments);
return result;
};
}
function arrayReplace(array, replacement) {
array.splice(0, array.length, ...replacement);
}