简体   繁体   中英

How to test child React component created in Render with React.createElement()

I am trying to test a custom react element built on top of some ad-hoc React elements Code:

return (
    React.createElement("div", {className: classes},
        React.createElement(TextField, {  
            ref: "omniTextBox",
            className: "menu-textfield",
            onChange: this._onControlChange
        }),
    )
);

this._onControlChange manipulates state based on textfield value. It is what I want to test, with different input to the textfield triggering different state of component.

Jest code:

var customComponent = TestUtils.renderIntoDocument( <CustomField /> );
var customField = TestUtils.findRenderedComponentWithType(customComponent, customField);
TestUtils.Simulate.change(customField, {target: {value: 'Hello, world'}});

I tried to mock function for _onControlChange to see if it is called, it is called 0 times. I also tried to see state of the customField var before and after simulate() call, and nothing changes. I wonder if I am missing something to simulate typing in a text field

I have tried all of the options to select by tag, type and class to no success. I can see the textfield element when console.log the rendered component. Is there any way to grab an instance of TextField via the ref?

You seem to have misused TestUtils.findRenderedComponentWithType . The input field in your custom component is actually a TextField .

var txtField = TestUtils.findRenderedComponentWithType(customComponent, TextField);
TestUtils.Simulate.change(txtField, {target: {value: 'Hello, world'}});

You were also redefining customField , thus why I changed the variable name here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM