Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 660
Shaheen Ghiassy Avatar asked Aug 14 '15 22:08

Shaheen Ghiassy


3 Answers

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

like image 198
aksonov Avatar answered Oct 19 '22 08:10

aksonov


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

like image 38
ertrzyiks Avatar answered Oct 19 '22 09:10

ertrzyiks


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

like image 1
Shaheen Ghiassy Avatar answered Oct 19 '22 08:10

Shaheen Ghiassy