Give context for owners of compenent instantiations with propType errors

See modification to the test-file: Basically we add a small hint at the end
of the error warning for propType errors to help identify which instantiation
of the component at hand is faulty.
This commit is contained in:
Yuval Dekel
2014-07-02 12:47:26 -07:00
committed by Paul O’Shannessy
parent 17aef05d75
commit 40b522c498
2 changed files with 39 additions and 1 deletions
+14 -1
View File
@@ -385,6 +385,15 @@ var RESERVED_SPEC_KEYS = {
}
};
function getDeclarationErrorAddendum(component) {
var owner = component._owner || null;
if (owner && owner.constructor && owner.constructor.displayName) {
return ' Check the render method of `' + owner.constructor.displayName +
'`.';
}
return '';
}
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
@@ -967,7 +976,11 @@ var ReactCompositeComponentMixin = {
var error =
propTypes[propName](props, propName, componentName, location);
if (error instanceof Error) {
warning(false, error.message);
// We may want to extend this logic for similar errors in
// renderComponent calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
warning(false, error.message + addendum);
}
}
}
@@ -110,6 +110,31 @@ describe('ReactCompositeComponent', function() {
console.warn = warn;
});
it('should give context for PropType errors in nested components.', () => {
// In this test, we're making sure that if a proptype error is found in a
// component, we give a smal hint as to which parent instantiated that
// component as per warnings about key-usage in ReactDescriptorValidator.
spyOn(console, 'warn');
var MyComp = React.createClass({
propTypes: {
color: ReactPropTypes.string
},
render: function() {
return <div>My color is {this.color}</div>;
}
});
var ParentComp = React.createClass({
render: function() {
return <MyComp color={123} />;
}
});
ReactTestUtils.renderIntoDocument(<ParentComp />);
expect(console.warn.calls[0].args[0]).toBe(
'Warning: Invalid prop `color` of type `number` supplied to `MyComp`, ' +
'expected `string`. Check the render method of `ParentComp`.'
);
});
it('should support rendering to different child types over time', function() {
var instance = <MorphingComponent />;
instance = ReactTestUtils.renderIntoDocument(instance);