forked from enzymejs/enzyme
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactWrapperComponent.jsx
More file actions
93 lines (82 loc) · 2.73 KB
/
ReactWrapperComponent.jsx
File metadata and controls
93 lines (82 loc) · 2.73 KB
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
import React, { PropTypes } from 'react';
import objectAssign from 'object.assign';
/**
* This is a utility component to wrap around the nodes we are
* passing in to `mount()`. Theoretically, you could do everything
* we are doing without this, but this makes it easier since
* `renderIntoDocument()` doesn't really pass back a reference to
* the DOM node it rendered to, so we can't really "re-render" to
* pass new props in.
*/
export default function createWrapperComponent(node, options = {}) {
const spec = {
propTypes: {
Component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired,
props: PropTypes.object.isRequired,
context: PropTypes.object,
},
getDefaultProps() {
return {
context: null,
};
},
getInitialState() {
return {
mount: true,
props: this.props.props,
context: this.props.context,
};
},
setChildProps(newProps) {
const props = objectAssign({}, this.state.props, newProps);
this.setState({ props });
},
setChildContext(context) {
return new Promise(resolve => this.setState({ context }, resolve));
},
getInstance() {
const component = this._reactInternalInstance._renderedComponent;
const inst = component.getPublicInstance();
if (inst === null) {
throw new Error(
`You cannot get an instance of a stateless component.`
);
}
return inst;
},
getWrappedComponent() {
const component = this._reactInternalInstance._renderedComponent;
const inst = component.getPublicInstance();
if (inst === null) {
return component;
}
return inst;
},
render() {
const { Component } = this.props;
const { mount, props } = this.state;
if (!mount) return null;
return (
<Component {...props} />
);
},
};
if (options.context && (node.type.contextTypes || options.childContextTypes)) {
// For full rendering, we are using this wrapper component to provide context if it is
// specified in both the options AND the child component defines `contextTypes` statically
// OR the merged context types for all children (the node component or deeper children) are
// specified in options parameter under childContextTypes.
// In that case, we define both a `getChildContext()` function and a `childContextTypes` prop.
const childContextTypes = node.type.contextTypes || {};
if (options.childContextTypes) {
objectAssign(childContextTypes, options.childContextTypes);
}
objectAssign(spec, {
childContextTypes,
getChildContext() {
return this.state.context;
},
});
}
return React.createClass(spec);
}