Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing touch events in react native

I am trying to test drive react native code using this guide. The react native is overridden by reactjs to enable shallow rendering and testing using jestjs.

Even though I am able test shallow rendered components (checking its presence and children), I am unable to test touch events.

handleTouch() {
 this.setState({ showDescription: !this.state.showDescription });
}


render() {
const description = this.state.showDescription ? (<Text style={styles.description}>{this.props.entry.description}</Text>) : null;
return (
  <TouchableNativeFeedback onPress={() => this.handleTouch()}>
    <View style={styles.rowContainer}>
      <View style={styles.row}>
      </View>
      {description}
    </View>
  </TouchableNativeFeedback>
 )
}

I'm trying to test if on touch of TouchableNativeFeedback, description tag is rendered. The reactjs TestUtils provides Simulate but it didn't work.

This is my spec setup:

beforeEach(function() {
    profileView = TestUtils.renderIntoDocument(<ProfileEntryView entry={entry}/>);
    var touchableNativeFeedback = TestUtils.findRenderedComponentWithType(profileView, TouchableNativeFeedback);
    TestUtils.Simulate.onTouchEnd(touchableNativeFeedback);
});

How will I test UI interactions using reactjs TestUtils for react-native?

like image 763
gmuraleekrishna Avatar asked Feb 01 '16 19:02

gmuraleekrishna


1 Answers

Because ReactTestUtils simulate does not have onTouchEnd or onPress event. So you need to add to mock object mocks/react-native.js:

const NativeComponent = (type) => {
    return React.createClass({
        render() {
            var properties = {className: type};
            if (typeof this.props.onPress !== 'undefined') {
                properties.onClick = this.props.onPress;
            }
            Object.assign(properties, this.props);
            return (
                <div {...properties}>{this.props.children}</div>
            );
      }
};
...
ReactNative.TouchableNativeFeedback = NativeComponent("TouchableNativeFeedback");

And update your test code to:

var touchableNativeFeedback = TestUtils.findRenderedDOMComponentWithClass(profileView, 'TouchableNativeFeedback');
TestUtils.Simulate.click(touchableNativeFeedback);

Looking for more code from this page.

like image 115
DoanND Avatar answered Nov 16 '22 00:11

DoanND