From 2d5142bc35b1df0103b671f5f236e5a4b86d3171 Mon Sep 17 00:00:00 2001 From: Pete Hunt Date: Mon, 18 Nov 2013 10:40:58 -0800 Subject: [PATCH] Better error message for renderComponentToString() Reported on Twitter by AirBnb (who are integrating React into their open-source JS framework). They made a mistake and passed a string in as the component. We should have a better error message for that. --- src/environment/ReactServerRendering.js | 18 ++++++++++++-- .../__tests__/ReactServerRendering-test.js | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/environment/ReactServerRendering.js b/src/environment/ReactServerRendering.js index 626cf117b0..e5046edbeb 100644 --- a/src/environment/ReactServerRendering.js +++ b/src/environment/ReactServerRendering.js @@ -18,17 +18,31 @@ */ "use strict"; +var ReactComponent = require('ReactComponent'); +var ReactInstanceHandles = require('ReactInstanceHandles'); var ReactMarkupChecksum = require('ReactMarkupChecksum'); var ReactReconcileTransaction = require('ReactReconcileTransaction'); -var ReactInstanceHandles = require('ReactInstanceHandles'); + +var invariant = require('invariant'); /** - * @param {object} component + * @param {ReactComponent} component * @param {function} callback */ function renderComponentToString(component, callback) { // We use a callback API to keep the API async in case in the future we ever // need it, but in reality this is a synchronous operation. + + invariant( + ReactComponent.isValidComponent(component), + 'renderComponentToString(): You must pass a valid ReactComponent.' + ); + + invariant( + typeof callback === 'function', + 'renderComponentToString(): You must pass a function as a callback.' + ); + var id = ReactInstanceHandles.createReactRootID(); var transaction = ReactReconcileTransaction.getPooled(); transaction.reinitializeTransaction(); diff --git a/src/environment/__tests__/ReactServerRendering-test.js b/src/environment/__tests__/ReactServerRendering-test.js index f019bb6f34..c208eadc56 100644 --- a/src/environment/__tests__/ReactServerRendering-test.js +++ b/src/environment/__tests__/ReactServerRendering-test.js @@ -228,4 +228,28 @@ describe('ReactServerRendering', function() { ReactTestUtils.Simulate.click(instance.refs.span.getDOMNode()); expect(numClicks).toEqual(1); }); + + it('should throw with silly args', function() { + expect( + ReactServerRendering.renderComponentToString.bind( + ReactServerRendering, + 'not a component', + function() {} + ) + ).toThrow( + 'Invariant Violation: renderComponentToString(): You must pass ' + + 'a valid ReactComponent.' + ); + + expect( + ReactServerRendering.renderComponentToString.bind( + ReactServerRendering, + React.DOM.div(), + 'not a function' + ) + ).toThrow( + 'Invariant Violation: renderComponentToString(): You must pass ' + + 'a function as a callback.' + ); + }); });