单元测试反应原生的触摸事件

时间:2016-02-01 19:45:15

标签: tdd ecmascript-6 react-native jestjs

我正在尝试使用this指南测试驱动器对本机代码的反应。 reactjs会覆盖react native,以便使用jestjs进行浅层渲染和测试。

即使我能够测试浅层渲染组件(检查其存在和子项),我也无法测试触摸事件。

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>
 )
}

我正在尝试测试是否触摸了TouchableNativeFeedbackdescription标记。 reactjs TestUtils提供Simulate,但它不起作用。

这是我的规格设置:

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

如何使用reactjs TestUtils为react-native测试UI交互?

1 个答案:

答案 0 :(得分:6)

因为ReactTestUtils模拟没有onTouchEndonPress事件。所以你需要添加到模拟对象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");

并将测试代码更新为:

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

寻找更多代码from this page