【问题标题】:How to test React Native components如何测试 React Native 组件
【发布时间】:2015-08-14 22:05:19
【问题描述】:

我正在尝试弄清楚如何测试 React Native(不是 React JS)组件。即使看 React Native 的入门代码,也很难看出如何测试它。

var AwesomeProject = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

我已经能够使用 Babel 转译 JSX 语法以及使用 Mockery 模拟 React 库方法 createClassStyleSheet.create,但最终,我似乎无法创建任何有意义的测试。

【问题讨论】:

标签: unit-testing react-native


【解决方案1】:

你应该模拟 React Native 包以及设置 babel 转换器和其他一些设置。也许您可以检查我的组件 React Native Router Flux 的单元测试:

https://github.com/aksonov/react-native-router-flux/tree/master/tests

【讨论】:

    【解决方案2】:

    要使用 Jest 运行测试,您应该使用 __mocks__ 文件夹将 ReactNative 替换为 React,使用带有浅渲染器的 TestUtils 并可能使用 react-shallow-renderer-helpers 来查找虚拟树。

    我制作了带有单元测试的示例存储库here 以及关于我如何通过它的文章here

    【讨论】:

      【解决方案3】:

      最后,我使用 Mocha 为 BDD 样式单元测试设置了一个带有 TravisCI 的 repo。您可以在以下位置查看 repo:https://github.com/sghiassy/react-native-sglistview

      【讨论】:

        【解决方案4】:

        看看 ReactNative 的 UIExplorer 示例项目,它设置了几个混合 XCTest 和 require('NativeModules').TestModule 测试套件。

        https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/UIExplorerIntegrationTests/js

        【讨论】:

        • 那些测试似乎不是用 Javascript 编写的。我想我们正在寻找 JS 单元测试。
        • 我更改了 URL 以将您直接带到 ES6 文件。
        • 链接 404 的现在
        猜你喜欢
        • 1970-01-01
        • 2019-10-30
        • 2019-01-15
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 2019-10-03
        • 2021-04-27
        • 2018-02-09
        相关资源
        最近更新 更多