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

gmu*_*hna 8 tdd ecmascript-6 jestjs react-native

我正在尝试使用指南测试驱动器反应本机代码.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>
 )
}
Run Code Online (Sandbox Code Playgroud)

我试图测试是否触摸TouchableNativeFeedback,description标记被渲染.reactjs TestUtils提供Simulate但它不起作用.

这是我的规格设置:

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

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

Doa*_*nND 6

因为ReactTestUtils模拟没有onTouchEndonPress事件.所以你需要添加到mock对象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");
Run Code Online (Sandbox Code Playgroud)

并将您的测试代码更新为:

var touchableNativeFeedback = TestUtils.findRenderedDOMComponentWithClass(profileView, 'TouchableNativeFeedback');
TestUtils.Simulate.click(touchableNativeFeedback);
Run Code Online (Sandbox Code Playgroud)

正在寻找此页面的更多代码.