Skip to content

Commit f4d7feb

Browse files
committed
Better error for invalid element when shallow rendering
Fixes facebook#4721, fixes facebook#4730.
1 parent 72d5b8f commit f4d7feb

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/test/ReactTestUtils.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,22 @@ assign(
396396
);
397397

398398
ReactShallowRenderer.prototype.render = function(element, context) {
399+
invariant(
400+
ReactElement.isValidElement(element),
401+
'ReactShallowRenderer render(): Invalid component element.%s',
402+
typeof element === 'function' ?
403+
' Instead of passing a component class, make sure to instantiate ' +
404+
'it by passing it to React.createElement.' :
405+
''
406+
);
407+
invariant(
408+
typeof element.type !== 'string',
409+
'ReactShallowRenderer render(): Shallow rendering works only with custom ' +
410+
'components, not primitives (%s). Instead of calling `.render(el)` and ' +
411+
'inspecting the rendered output, look at `el.props` directly instead.',
412+
element.type
413+
);
414+
399415
if (!context) {
400416
context = emptyObject;
401417
}

src/test/__tests__/ReactTestUtils-test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,27 @@ describe('ReactTestUtils', function() {
5353
]);
5454
});
5555

56+
it('should throw for invalid elements', function() {
57+
var SomeComponent = React.createClass({
58+
render: function() {
59+
return <div />;
60+
},
61+
});
62+
63+
var shallowRenderer = ReactTestUtils.createRenderer();
64+
expect(() => shallowRenderer.render(SomeComponent)).toThrow(
65+
'Invariant Violation: ReactShallowRenderer render(): Invalid component ' +
66+
'element. Instead of passing a component class, make sure to ' +
67+
'instantiate it by passing it to React.createElement.'
68+
);
69+
expect(() => shallowRenderer.render(<div />)).toThrow(
70+
'Invariant Violation: ReactShallowRenderer render(): Shallow rendering ' +
71+
'works only with custom components, not primitives (div). Instead of ' +
72+
'calling `.render(el)` and inspecting the rendered output, look at ' +
73+
'`el.props` directly instead.'
74+
);
75+
});
76+
5677
it('should have shallow unmounting', function() {
5778
var componentWillUnmount = mocks.getMockFunction();
5879

0 commit comments

Comments
 (0)