-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
utils.js
357 lines (310 loc) · 8.95 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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
* 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 strict-local
*/
import type {
AsyncFn,
BlockMode,
BlockName,
DescribeBlock,
Exception,
Hook,
RunResult,
TestEntry,
TestContext,
TestFn,
TestMode,
TestName,
TestResults,
} from 'types/Circus';
import {convertDescriptorToString} from 'jest-util';
import isGeneratorFn from 'is-generator-fn';
import co from 'co';
import StackUtils from 'stack-utils';
import prettyFormat from 'pretty-format';
import {getState} from './state';
// Try getting the real promise object from the context, if available. Someone
// could have overridden it in a test. Async functions return it implicitly.
// eslint-disable-next-line no-unused-vars
const Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
export const getOriginalPromise = () => Promise;
const stackUtils = new StackUtils({cwd: 'A path that does not exist'});
export const makeDescribe = (
name: BlockName,
parent: ?DescribeBlock,
mode?: BlockMode,
): DescribeBlock => {
let _mode = mode;
if (parent && !mode) {
// If not set explicitly, inherit from the parent describe.
_mode = parent.mode;
}
return {
children: [],
hooks: [],
mode: _mode,
name: convertDescriptorToString(name),
parent,
tests: [],
};
};
export const makeTest = (
fn: ?TestFn,
mode: TestMode,
name: TestName,
parent: DescribeBlock,
timeout: ?number,
asyncError: Exception,
): TestEntry => {
let _mode = mode;
if (!mode) {
// if not set explicitly, inherit from its parent describe
_mode = parent.mode;
}
return {
asyncError,
duration: null,
errors: [],
fn,
invocations: 0,
mode: _mode,
name: convertDescriptorToString(name),
parent,
startedAt: null,
status: null,
timeout,
};
};
// Traverse the tree of describe blocks and return true if at least one describe
// block has an enabled test.
const hasEnabledTest = (describeBlock: DescribeBlock): boolean => {
const {hasFocusedTests, testNamePattern} = getState();
const hasOwnEnabledTests = describeBlock.tests.some(
test =>
!(
test.mode === 'skip' ||
(hasFocusedTests && test.mode !== 'only') ||
(testNamePattern && !testNamePattern.test(getTestID(test)))
),
);
return hasOwnEnabledTests || describeBlock.children.some(hasEnabledTest);
};
export const getAllHooksForDescribe = (
describe: DescribeBlock,
): {[key: 'beforeAll' | 'afterAll']: Array<Hook>} => {
const result = {afterAll: [], beforeAll: []};
if (hasEnabledTest(describe)) {
for (const hook of describe.hooks) {
switch (hook.type) {
case 'beforeAll':
result.beforeAll.push(hook);
break;
case 'afterAll':
result.afterAll.push(hook);
break;
}
}
}
return result;
};
export const getEachHooksForTest = (
test: TestEntry,
): {[key: 'beforeEach' | 'afterEach']: Array<Hook>} => {
const result = {afterEach: [], beforeEach: []};
let {parent: block} = test;
do {
const beforeEachForCurrentBlock = [];
for (const hook of block.hooks) {
switch (hook.type) {
case 'beforeEach':
beforeEachForCurrentBlock.push(hook);
break;
case 'afterEach':
result.afterEach.push(hook);
break;
}
}
// 'beforeEach' hooks are executed from top to bottom, the opposite of the
// way we traversed it.
result.beforeEach = [...beforeEachForCurrentBlock, ...result.beforeEach];
} while ((block = block.parent));
return result;
};
export const describeBlockHasTests = (describe: DescribeBlock) =>
describe.tests.length || describe.children.some(describeBlockHasTests);
const _makeTimeoutMessage = (timeout, isHook) =>
`Exceeded timeout of ${timeout}ms for a ${
isHook ? 'hook' : 'test'
}.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`;
// Global values can be overwritten by mocks or tests. We'll capture
// the original values in the variables before we require any files.
const {setTimeout, clearTimeout} = global;
export const callAsyncFn = (
fn: AsyncFn,
testContext: ?TestContext,
{isHook, timeout}: {isHook?: ?boolean, timeout: number},
): Promise<mixed> => {
let timeoutID;
return new Promise((resolve, reject) => {
timeoutID = setTimeout(
() => reject(_makeTimeoutMessage(timeout, isHook)),
timeout,
);
// If this fn accepts `done` callback we return a promise that fulfills as
// soon as `done` called.
if (fn.length) {
const done = (reason?: Error | string): void => {
// $FlowFixMe: It doesn't approve of .stack
const isError = reason && reason.message && reason.stack;
return reason
? reject(
isError
? reason
: new Error(`Failed: ${prettyFormat(reason, {maxDepth: 3})}`),
)
: resolve();
};
return fn.call(testContext, done);
}
let returnedValue;
if (isGeneratorFn(fn)) {
returnedValue = co.wrap(fn).call({});
} else {
try {
returnedValue = fn.call(testContext);
} catch (error) {
return reject(error);
}
}
// If it's a Promise, return it. Test for an object with a `then` function
// to support custom Promise implementations.
if (
typeof returnedValue === 'object' &&
returnedValue !== null &&
typeof returnedValue.then === 'function'
) {
return returnedValue.then(resolve, reject);
}
if (!isHook && returnedValue !== void 0) {
return reject(
new Error(
`
test functions can only return Promise or undefined.
Returned value: ${String(returnedValue)}
`,
),
);
}
// Otherwise this test is synchronous, and if it didn't throw it means
// it passed.
return resolve();
})
.then(() => {
// If timeout is not cleared/unrefed the node process won't exit until
// it's resolved.
timeoutID.unref && timeoutID.unref();
clearTimeout(timeoutID);
})
.catch(error => {
timeoutID.unref && timeoutID.unref();
clearTimeout(timeoutID);
throw error;
});
};
export const getTestDuration = (test: TestEntry): ?number => {
const {startedAt} = test;
return startedAt ? Date.now() - startedAt : null;
};
export const makeRunResult = (
describeBlock: DescribeBlock,
unhandledErrors: Array<Error>,
): RunResult => ({
testResults: makeTestResults(describeBlock),
unhandledErrors: unhandledErrors.map(_formatError),
});
const makeTestResults = (describeBlock: DescribeBlock, config): TestResults => {
const {includeTestLocationInResult} = getState();
let testResults = [];
for (const test of describeBlock.tests) {
const testPath = [];
let parent = test;
do {
testPath.unshift(parent.name);
} while ((parent = parent.parent));
const {status} = test;
if (!status) {
throw new Error('Status should be present after tests are run.');
}
let location = null;
if (includeTestLocationInResult) {
const stackLine = test.asyncError.stack.split('\n')[1];
const {line, column} = stackUtils.parseLine(stackLine);
location = {column, line};
}
testResults.push({
duration: test.duration,
errors: test.errors.map(_formatError),
invocations: test.invocations,
location,
status,
testPath,
});
}
for (const child of describeBlock.children) {
testResults = testResults.concat(makeTestResults(child, config));
}
return testResults;
};
// Return a string that identifies the test (concat of parent describe block
// names + test title)
export const getTestID = (test: TestEntry) => {
const titles = [];
let parent = test;
do {
titles.unshift(parent.name);
} while ((parent = parent.parent));
titles.shift(); // remove TOP_DESCRIBE_BLOCK_NAME
return titles.join(' ');
};
const _formatError = (errors: ?Exception | [?Exception, Exception]): string => {
let error;
let asyncError;
if (Array.isArray(errors)) {
error = errors[0];
asyncError = errors[1];
} else {
error = errors;
asyncError = new Error();
}
if (error) {
if (error.stack) {
return error.stack;
}
if (error.message) {
return error.message;
}
}
asyncError.message = `thrown: ${prettyFormat(error, {maxDepth: 3})}`;
return asyncError.stack;
};
export const addErrorToEachTestUnderDescribe = (
describeBlock: DescribeBlock,
error: Exception,
asyncError: Exception,
) => {
for (const test of describeBlock.tests) {
test.errors.push([error, asyncError]);
}
for (const child of describeBlock.children) {
addErrorToEachTestUnderDescribe(child, error, asyncError);
}
};
export const invariant = (condition: *, message: string) => {
if (!condition) {
throw new Error(message);
}
};