简体   繁体   中英

How to test React Native components

I'm trying to figure out how to test React Native (not React JS) components. Even looking at React Native's starter code, its difficult to see how to test it.

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

I've been able to use Babel to transpile the JSX syntax as well as use Mockery to mock the React library methods createClass and StyleSheet.create , but at the end of the day, I can't seem to create any meaningful tests.

You should mock up React Native package as well as set babel transformer and some other settings. Maybe you could check unit tests for my component, React Native Router Flux:

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

To run tests with Jest you should replace ReactNative with React using __mocks__ folder, use TestUtils with shallow renderer and maybe react-shallow-renderer-helpers to lookup virtual tree.

I've made sample repository with unit tests here and article about my way through it here

In the end I setup a repo with TravisCI using Mocha for BDD style unit tests. You can see the repo at: https://github.com/sghiassy/react-native-sglistview

Take a look at ReactNative's UIExplorer example project, which is set up with several hybrid XCTest & require('NativeModules').TestModule test suites.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM