【问题标题】:Unit testing touch events in react native在本机反应中单元测试触摸事件
【发布时间】:2016-05-10 09:39:40
【问题描述】:

我正在尝试使用this 指南测试驱动反应本机代码。 react native 被 reactjs 覆盖,可以使用 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 交互?

【问题讨论】:

    标签: tdd ecmascript-6 react-native jestjs


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多