Skip to content

Instantly share code, notes, and snippets.

@localnerve
Created December 22, 2015 18:47
Show Gist options
  • Save localnerve/26a8d3b16fefe16bf26c to your computer and use it in GitHub Desktop.
Save localnerve/26a8d3b16fefe16bf26c to your computer and use it in GitHub Desktop.
React 0.14.x HTML Element, Replacement for ReactTestUtils.renderIntoDocument, React / jsDom / Unit Testing

React 0.14.x TestUtils.renderIntoDocument replacement for html elements

  /**
   * renderIntoDocument for html element.
   * Replaces testUtils.renderIntoDocument.
   *
   * testUtils.renderIntoDocument no longer supports React html components as it wraps
   * everything in a div:
   * https://github.com/facebook/react/issues/5128
   *
   * 1. This is for a nodejs unit test environment.
   * 2. Must start jsdom first.
   * 3. Handy in beforeEach type hook.
   *
   * @param {ReactElement} el - The html element.
   * @returns {ReactComponent} The html component, for use in ReactTestUtils methods.
   */
  function renderHtmlIntoDocument (el) {
    var ReactDOM = require('react-dom');
    var ReactDOMServer = require('react-dom/server');

    var iframe = global.document.createElement('iframe');

    global.document.body.appendChild(iframe);
  
    iframe.src = 'about:blank';
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(ReactDOMServer.renderToString(el));
    iframe.contentWindow.document.close();
    return ReactDOM.render(el, iframe.contentWindow.document);
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment