Ad

React Shallow Rendering Generates Component With Type == Function Instead Of Type ==

- 1 answer

Assuming the following 2 components

var Level2 = React.createClass({
  render: function () {
    return      React.createElement('div');
  }

});

var Level1 = React.createClass({
    render: function () {
        return      React.createElement(Level2);
    }
});

and the following helper for shallow rendering testing in Jasmine

var TestUtils = React.addons.TestUtils;

var shallowRender = function(element, props, children) {
    var ShallowRenderer = TestUtils.createRenderer();
    ShallowRenderer.render(React.createElement(element, props, children));
    return ShallowRenderer.getRenderOutput();
};

The second test does not behave as I expect:

describe ('test rendered output', function (){
    it('level 2 should render a div component', function() {
       l2 = shallowRender(Level2);
        expect(l2.type).toBe('div')   // this test PASSES
    });

    it('level 1 should render a level 2 component', function() {
        l1 = shallowRender(Level1);
        // this test FAILS with the following message  'Expected Function to be 'Level2'
        expect(l1.type).toBe('Level2')  
    })
});

Any idea why the second test fails ?

Ad

Answer

When you type a JSX tag name with a lowercase letter

<div />

the JSX is transpiled into

React.createClass("div")

and thus the element type is a string — "div". But when you use an uppercase letter

<Level2 />

the JSX turns into

React.createClass(Level2)

and the type of the component is not a string (e.g. "Level2"), but is in fact the actual value Level2. Your test should read

expect(l1.type).toBe(Level2)
Ad
source: stackoverflow.com
Ad