-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
jestAdapterInit.ts
295 lines (263 loc) · 8.13 KB
/
jestAdapterInit.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
/**
* 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 type {Circus, Config, Global} from '@jest/types';
import type {JestEnvironment} from '@jest/environment';
import {
AssertionResult,
Status,
TestResult,
createEmptyTestResult,
} from '@jest/test-result';
import {extractExpectedAssertionsErrors, getState, setState} from 'expect';
import {formatExecError, formatResultsErrors} from 'jest-message-util';
import type {TestFileEvent} from 'jest-runner';
import {
SnapshotState,
SnapshotStateType,
addSerializer,
buildSnapshotResolver,
} from 'jest-snapshot';
import {bind} from 'jest-each';
import throat from 'throat';
import {
ROOT_DESCRIBE_BLOCK_NAME,
addEventHandler,
dispatch,
getState as getRunnerState,
} from '../state';
import {getTestID} from '../utils';
import run from '../run';
import testCaseReportHandler from '../testCaseReportHandler';
import globals from '..';
type Process = NodeJS.Process;
// TODO: hard to type
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const initialize = async ({
config,
environment,
getPrettier,
getBabelTraverse,
globalConfig,
localRequire,
parentProcess,
testPath,
sendMessageToJest,
}: {
config: Config.ProjectConfig;
environment: JestEnvironment;
getPrettier: () => null | any;
getBabelTraverse: () => Function;
globalConfig: Config.GlobalConfig;
localRequire: (path: Config.Path) => any;
testPath: Config.Path;
parentProcess: Process;
sendMessageToJest?: TestFileEvent;
}) => {
if (globalConfig.testTimeout) {
getRunnerState().testTimeout = globalConfig.testTimeout;
}
const mutex = throat(globalConfig.maxConcurrency);
const nodeGlobal = global as Global.Global;
Object.assign(nodeGlobal, globals);
nodeGlobal.xit = nodeGlobal.it.skip;
nodeGlobal.xtest = nodeGlobal.it.skip;
nodeGlobal.xdescribe = nodeGlobal.describe.skip;
nodeGlobal.fit = nodeGlobal.it.only;
nodeGlobal.fdescribe = nodeGlobal.describe.only;
nodeGlobal.test.concurrent = (test => {
const concurrent = (
testName: string,
testFn: () => Promise<unknown>,
timeout?: number,
) => {
// For concurrent tests we first run the function that returns promise, and then register a
// nomral test that will be waiting on the returned promise (when we start the test, the promise
// will already be in the process of execution).
// Unfortunately at this stage there's no way to know if there are any `.only` tests in the suite
// that will result in this test to be skipped, so we'll be executing the promise function anyway,
// even if it ends up being skipped.
const promise = mutex(() => testFn());
nodeGlobal.test(testName, () => promise, timeout);
};
const only = (
testName: string,
testFn: () => Promise<unknown>,
timeout?: number,
) => {
const promise = mutex(() => testFn());
// eslint-disable-next-line jest/no-focused-tests
test.only(testName, () => promise, timeout);
};
concurrent.only = only;
concurrent.skip = test.skip;
concurrent.each = bind(test, false);
concurrent.skip.each = bind(test.skip, false);
only.each = bind(test.only, false);
return concurrent;
})(nodeGlobal.test);
addEventHandler(eventHandler);
if (environment.handleTestEvent) {
addEventHandler(environment.handleTestEvent.bind(environment));
}
await dispatch({
name: 'setup',
parentProcess,
testNamePattern: globalConfig.testNamePattern,
});
if (config.testLocationInResults) {
await dispatch({
name: 'include_test_location_in_result',
});
}
// Jest tests snapshotSerializers in order preceding built-in serializers.
// Therefore, add in reverse because the last added is the first tested.
config.snapshotSerializers
.concat()
.reverse()
.forEach(path => {
addSerializer(localRequire(path));
});
const {expand, updateSnapshot} = globalConfig;
const snapshotResolver = buildSnapshotResolver(config);
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
const snapshotState = new SnapshotState(snapshotPath, {
expand,
getBabelTraverse,
getPrettier,
updateSnapshot,
});
setState({snapshotState, testPath});
addEventHandler(handleSnapshotStateAfterRetry(snapshotState));
if (sendMessageToJest) {
addEventHandler(testCaseReportHandler(testPath, sendMessageToJest));
}
// Return it back to the outer scope (test runner outside the VM).
return {globals, snapshotState};
};
export const runAndTransformResultsToJestFormat = async ({
config,
globalConfig,
testPath,
}: {
config: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
testPath: string;
}): Promise<TestResult> => {
const runResult: Circus.RunResult = await run();
let numFailingTests = 0;
let numPassingTests = 0;
let numPendingTests = 0;
let numTodoTests = 0;
const assertionResults: Array<AssertionResult> = runResult.testResults.map(
testResult => {
let status: Status;
if (testResult.status === 'skip') {
status = 'pending';
numPendingTests += 1;
} else if (testResult.status === 'todo') {
status = 'todo';
numTodoTests += 1;
} else if (testResult.errors.length) {
status = 'failed';
numFailingTests += 1;
} else {
status = 'passed';
numPassingTests += 1;
}
const ancestorTitles = testResult.testPath.filter(
name => name !== ROOT_DESCRIBE_BLOCK_NAME,
);
const title = ancestorTitles.pop();
return {
ancestorTitles,
duration: testResult.duration,
failureDetails: testResult.errorsDetailed,
failureMessages: testResult.errors,
fullName: title
? ancestorTitles.concat(title).join(' ')
: ancestorTitles.join(' '),
invocations: testResult.invocations,
location: testResult.location,
numPassingAsserts: 0,
status,
title: testResult.testPath[testResult.testPath.length - 1],
};
},
);
let failureMessage = formatResultsErrors(
assertionResults,
config,
globalConfig,
testPath,
);
let testExecError;
if (runResult.unhandledErrors.length) {
testExecError = {
message: '',
stack: runResult.unhandledErrors.join('\n'),
};
failureMessage =
(failureMessage || '') +
'\n\n' +
runResult.unhandledErrors
.map(err => formatExecError(err, config, globalConfig))
.join('\n');
}
await dispatch({name: 'teardown'});
return {
...createEmptyTestResult(),
console: undefined,
displayName: config.displayName,
failureMessage,
numFailingTests,
numPassingTests,
numPendingTests,
numTodoTests,
sourceMaps: {},
testExecError,
testFilePath: testPath,
testResults: assertionResults,
};
};
const handleSnapshotStateAfterRetry = (snapshotState: SnapshotStateType) => (
event: Circus.Event,
) => {
switch (event.name) {
case 'test_retry': {
// Clear any snapshot data that occurred in previous test run
snapshotState.clear();
}
}
};
const eventHandler = async (event: Circus.Event) => {
switch (event.name) {
case 'test_start': {
setState({currentTestName: getTestID(event.test)});
break;
}
case 'test_done': {
_addSuppressedErrors(event.test);
_addExpectedAssertionErrors(event.test);
break;
}
}
};
const _addExpectedAssertionErrors = (test: Circus.TestEntry) => {
const failures = extractExpectedAssertionsErrors();
const errors = failures.map(failure => failure.error);
test.errors = test.errors.concat(errors);
};
// Get suppressed errors from ``jest-matchers`` that weren't throw during
// test execution and add them to the test result, potentially failing
// a passing test.
const _addSuppressedErrors = (test: Circus.TestEntry) => {
const {suppressedErrors} = getState();
setState({suppressedErrors: []});
if (suppressedErrors.length) {
test.errors = test.errors.concat(suppressedErrors);
}
};