-
Notifications
You must be signed in to change notification settings - Fork 64
/
shallow.js
88 lines (70 loc) · 1.95 KB
/
shallow.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
import omitBy from 'lodash/omitBy';
import isNil from 'lodash/isNil';
import {isValidElementType} from 'react-is';
import {childrenOfNode, propsOfNode} from 'enzyme/build/RSTTraversal';
import {compact, applyMap, extractTypeName} from './utils';
function getChildren(node, options) {
const children = compact(
childrenOfNode(node).map(n => internalNodeToJson(n, options)),
);
if (children.length > 0) {
return children;
}
return null;
}
function getProps(node, options) {
const props = omitBy(Object.assign({}, propsOfNode(node)), (val, key) => {
if (key === 'children' || val === undefined) {
return true;
}
if (
options.ignoreDefaultProps === true &&
isValidElementType(node.type) &&
node.type.defaultProps &&
key in node.type.defaultProps &&
node.type.defaultProps[key] === val
) {
return true;
}
});
if (!isNil(node.key) && options.noKey !== true) {
props.key = node.key;
}
return props;
}
function internalNodeToJson(node, options) {
if (typeof node === 'string' || typeof node === 'number') {
return node;
}
if (isNil(node) || node === false) {
return '';
}
const json = applyMap(
{
node,
type: extractTypeName(node),
props: getProps(node, options),
children: getChildren(node, options),
$$typeof: Symbol.for('react.test.json'),
},
options,
);
if (!isNil(json) && !isNil(json.type)) {
return json;
}
}
const shallowToJson = (wrapper, options = {}) => {
if (isNil(wrapper) || wrapper.length === 0) {
return null;
}
if (wrapper.length > 1 && typeof wrapper.getNodesInternal === 'function') {
const nodes = wrapper.getNodesInternal();
return nodes.map(node => internalNodeToJson(node, options));
}
if (typeof wrapper.getNodeInternal === 'function') {
const node = wrapper.getNodeInternal();
return internalNodeToJson(node, options);
}
return null;
};
export default shallowToJson;