Search code examples
reactjsjestjsreactjs-testutils

Jest + React TestUtils: Render a <meta> tag with TestUtils.renderIntoDocument


I am writing a React component that depends on a meta tag of a specific name to be present in the head area of the DOM, so I'm trying to use TestUtils.renderIntoDocument to create that meta tag for running my Jest test, which is not working.

jest.dontMock('../channel-finder');

describe('Channel Finder Component', function() {
  it('Renders properly with no props', function() {

    var React = require('react/addons');
    var ChannelFinder = require('../channel-finder');
    var TestUtils = React.addons.TestUtils;

    // Render into Document
    var ChannelFinderComponent = TestUtils.renderIntoDocument(
      <ChannelFinder />
    );
    var ClientIpMetaTag = TestUtils.renderIntoDocument(
      <meta name="client-ip" content="50.200.28.114">
    );

    // Find Rendered DOM Component
    var ChannelFinderDomElement = TestUtils.findRenderedDOMComponentWithTag(ChannelFinderComponent, 'div');

    // Assert Results
    expect(ChannelFinderDomElement.getDOMNode().textContent).toEqual('');
  });
});

Can this be accomplished with either React TestUtils or React itself somehow?

Result is a super-long error stack trace: enter image description here

My preprocessor.js file:

// preprocessor.js
var ReactTools = require('react-tools');
module.exports = {
  process: function(src) {
    return ReactTools.transform(src);
  }
};

Solution

  • Thanks for pinging me on this, as it gave me motivation to revisit it, and it turns out the cryptic error message is no longer saying what it used to say, instead it says that my meta tag did not have a valid JSX termination (DUH!), so this is what made it work:

    var ClientIpMetaTag = TestUtils.renderIntoDocument(
        <meta name="client-ip" content="50.200.28.114" />
    );
    

    Just adding the slash before the right arrow made it valid JSX. I saw this more helpful message after I upgraded to React 0.13, which probably made improvements to the error messaging (i'm guessing).