Skip to content

ReactTestUtils.mockComponent does not pass props #2660

@awei01

Description

@awei01

In using mocked components in test, all props don't get passed to the ConvenienceConstructor mocked component. Only the this.props.children get passed. Is there a particular reason that this.props don't get passed as well? I think it would make asserting that certain props get passed down to the sub-module easier.

Looking at ReactTestUtils.js (https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js#L254):

mockComponent: function(module, mockTagName) {
    mockTagName = mockTagName || module.mockTagName || "div";

    var ConvenienceConstructor = React.createClass({displayName: 'ConvenienceConstructor',
      render: function() {
        return React.createElement(
          mockTagName,
          null, // why isn't this this.props to allow for assertions on passed props?
          this.props.children
        );
      }
    });

...

After doing a little more digging, I found some more info. Given the module:

module.exports = React.createClass({
    _renderItems: function() {
        return this.props.items.map(function(item, index) {
            return <Child key={ index } somePassedProp={ item }/>
        });
    },
    render: function() {
        var items = this._renderItems();
        return <Parent ref="parent" someProp="foo">{items}</Parent>;
    }
});

The props do get passed properly and can be asserted when accessing the mocked component using a named ref. Thus, you can assert that component.refs.props.someProp = "foo". However, unless I'm missing something, you cannot access all of the props of a sub-module that is iterated over: var children = TestUtils.scryRenderedDOMComponentsWithTag(component, 'CHILD'); children[0].props.somePassedProp will always be undefined.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions