ShallowRenderer should filter context by contextTypes (#11922)

This commit is contained in:
Toru Kobayashi
2018-01-05 18:49:57 +00:00
committed by Dan Abramov
parent 05da6c695b
commit 10bb5486a9
2 changed files with 41 additions and 6 deletions
+17 -6
View File
@@ -70,15 +70,15 @@ class ReactShallowRenderer {
this._rendering = true;
this._element = element;
this._context = context;
this._context = getMaskedContext(element.type.contextTypes, context);
if (this._instance) {
this._updateClassComponent(element.type, element.props, context);
this._updateClassComponent(element.type, element.props, this._context);
} else {
if (shouldConstruct(element.type)) {
this._instance = new element.type(
element.props,
context,
this._context,
this._updater,
);
@@ -87,7 +87,7 @@ class ReactShallowRenderer {
checkPropTypes(
element.type.contextTypes,
context,
this._context,
'context',
getName(element.type, this._instance),
getStackAddendum,
@@ -96,9 +96,9 @@ class ReactShallowRenderer {
currentlyValidatingElement = null;
}
this._mountClassComponent(element.props, context);
this._mountClassComponent(element.props, this._context);
} else {
this._rendered = element.type(element.props, context);
this._rendered = element.type(element.props, this._context);
}
}
@@ -290,4 +290,15 @@ function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function getMaskedContext(contextTypes, unmaskedContext) {
if (!contextTypes) {
return emptyObject;
}
const context = {};
for (let key in contextTypes) {
context[key] = unmaskedContext[key];
}
return context;
}
export default ReactShallowRenderer;
@@ -216,6 +216,9 @@ describe('ReactShallowRenderer', () => {
</div>
);
}
SomeComponent.contextTypes = {
bar: PropTypes.string,
};
const shallowRenderer = createRenderer();
const result = shallowRenderer.render(<SomeComponent foo={'FOO'} />, {
@@ -428,6 +431,9 @@ describe('ReactShallowRenderer', () => {
super(props, context);
this.state = initialState;
}
static contextTypes = {
context: PropTypes.string,
};
componentDidUpdate(...args) {
componentDidUpdateParams.push(...args);
}
@@ -770,6 +776,24 @@ describe('ReactShallowRenderer', () => {
expect(result).toEqual(<div>foo:baz</div>);
});
it('should filter context by contextTypes', () => {
class SimpleComponent extends React.Component {
static contextTypes = {
foo: PropTypes.string,
};
render() {
return <div>{`${this.context.foo}:${this.context.bar}`}</div>;
}
}
const shallowRenderer = createRenderer();
let result = shallowRenderer.render(<SimpleComponent />, {
foo: 'foo',
bar: 'bar',
});
expect(result).toEqual(<div>foo:undefined</div>);
});
it('can fail context when shallowly rendering', () => {
class SimpleComponent extends React.Component {
static contextTypes = {