-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
tree_processor.js
84 lines (74 loc) · 2.42 KB
/
tree_processor.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
/**
* 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
*/
type Options = {
nodeComplete: (suite: TreeNode) => void,
nodeStart: (suite: TreeNode) => void,
queueRunnerFactory: any,
runnableIds: Array<string>,
tree: TreeNode,
};
type TreeNode = {
afterAllFns: Array<any>,
beforeAllFns: Array<any>,
execute: (onComplete: () => void, enabled: boolean) => void,
id: string,
onException: (error: Error) => void,
sharedUserContext: () => any,
children?: Array<TreeNode>,
};
// 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 default function treeProcessor(options: Options) {
const {
nodeComplete,
nodeStart,
queueRunnerFactory,
runnableIds,
tree,
} = options;
function isEnabled(node, parentEnabled) {
return parentEnabled || runnableIds.indexOf(node.id) !== -1;
}
function getNodeHandler(node: TreeNode, parentEnabled: boolean) {
const enabled = isEnabled(node, parentEnabled);
return node.children
? getNodeWithChildrenHandler(node, enabled)
: getNodeWithoutChildrenHandler(node, enabled);
}
function getNodeWithoutChildrenHandler(node: TreeNode, enabled: boolean) {
return function fn(done: (error?: any) => void = () => {}) {
node.execute(done, enabled);
};
}
function getNodeWithChildrenHandler(node: TreeNode, enabled: boolean) {
return async function fn(done: (error?: any) => void = () => {}) {
nodeStart(node);
await queueRunnerFactory({
onException: error => node.onException(error),
queueableFns: wrapChildren(node, enabled),
userContext: node.sharedUserContext(),
});
nodeComplete(node);
done();
};
}
function wrapChildren(node: TreeNode, enabled: boolean) {
if (!node.children) {
throw new Error('`node.children` is not defined.');
}
const children = node.children.map(child => ({
fn: getNodeHandler(child, enabled),
}));
return node.beforeAllFns.concat(children).concat(node.afterAllFns);
}
const treeHandler = getNodeHandler(tree, false);
return treeHandler();
}