Skip to content

Commit fc07a84

Browse files
committed
add option for childContextTypes of ReactWrapper
Fixes #144.
1 parent ac165c8 commit fc07a84

3 files changed

Lines changed: 34 additions & 1 deletion

File tree

docs/api/mount.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ describe('<Foo />', () => {
4545
2. `options` (`Object` [optional]):
4646
- `options.context`: (`Object` [optional]): Context to be passed into the component
4747
- `options.attachTo`: (`DOMElement` [optional]): DOM Element to attach the component to.
48+
- `options.childContextTypes`: (`Object` [optional]): Merged contextTypes for all children of the wrapper.
4849

4950
#### Returns
5051

src/ReactWrapperComponent.jsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,12 @@ export default function createWrapperComponent(node, options = {}) {
7575
// For full rendering, we are using this wrapper component to provide context if it is
7676
// specified in both the options AND the child component defines `contextTypes` statically.
7777
// In that case, we define both a `getChildContext()` function and a `childContextTypes` prop.
78+
let childContextTypes = node.type.contextTypes;
79+
if (options.childContextTypes) {
80+
childContextTypes = options.childContextTypes;
81+
}
7882
objectAssign(spec, {
79-
childContextTypes: node.type.contextTypes,
83+
childContextTypes,
8084
getChildContext() {
8185
return this.state.context;
8286
},

src/__tests__/ReactWrapper-spec.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,34 @@ describeWithDOM('mount', () => {
2828
expect(wrapper.text()).to.equal('foo');
2929
});
3030

31+
it('can pass advanced context to the child of mounted component', () => {
32+
const SimpleComponent = React.createClass({
33+
contextTypes: {
34+
ctx1: React.PropTypes.string.isRequired,
35+
ctx2: React.PropTypes.string.isRequired,
36+
},
37+
render() {
38+
return <div>{this.context.ctx1}{this.context.ctx2}</div>;
39+
},
40+
});
41+
const ComplexComponent = React.createClass({
42+
contextTypes: {
43+
ctx1: React.PropTypes.string.isRequired,
44+
},
45+
render() {
46+
return <div><SimpleComponent /><p>{this.context.ctx1}</p></div>;
47+
},
48+
});
49+
50+
const advancedContext = { ctx1: 'ctx1', ctx2: 'ctx2' };
51+
const childContextTypes = {
52+
ctx1: React.PropTypes.string.isRequired,
53+
ctx2: React.PropTypes.string.isRequired,
54+
};
55+
const wrapper = mount(<ComplexComponent />, { context: advancedContext, childContextTypes });
56+
expect(wrapper.find(SimpleComponent)).to.have.length(1);
57+
});
58+
3159
it('should not throw if context is passed in but contextTypes is missing', () => {
3260
const SimpleComponent = React.createClass({
3361
render() {

0 commit comments

Comments
 (0)