测试React Native程序
在 Facebook,我们使用 Jest 测试 React 应用。
阅读以下系列文章来深入了解如何使用 Jest 测试一个真实的 React Native 示例应用:第一篇: Jest – Snapshot come into play 和 第二篇: Jest – Redux Snapshots for your Actions and Reducers.
安装
Starting from react-native version 0.38, a Jest setup is included by default when running react-native init
. The following configuration should be automatically added to your package.json file: The following configuration should be automatically added to your package.json file:
{
"scripts": {
"test": "jest"
},
"jest": {
"preset": "react-native"
}
}
用 yarn test
来运行 Jest 测试。
If you are upgrading your react-native application and previously used the jest-react-native
preset, remove the dependency from your package.json
file and change the preset to react-native
instead.
Snapshot Test
下面来为一个入门的小型组件创建一个快照测试,它的内部有些View、Text组件和一些样式:
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
class Intro extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>
This is a React Native snapshot test.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
backgroundColor: '#F5FCFF',
flex: 1,
justifyContent: 'center',
},
instructions: {
color: '#333333',
marginBottom: 5,
textAlign: 'center',
},
welcome: {
fontSize: 20,
margin: 10,
textAlign: 'center',
},
});
export default Intro;
现在,使用React的test renderer和Jest的快照特性来和组件交互,获得渲染结果和生成快照文件:
import React from 'react';
import renderer from 'react-test-renderer';
import Intro from '../Intro';
test('renders correctly', () => {
const tree = renderer.create(<Intro />).toJSON();
expect(tree).toMatchSnapshot();
});
当你运行 npm test
或者 jest
,将产生一个像下面的文件:
exports[`Intro renders correctly 1`] = `
<View
style={
Object {
"alignItems": "center",
"backgroundColor": "#F5FCFF",
"flex": 1,
"justifyContent": "center",
}
}>
<Text
style={
Object {
"fontSize": 20,
"margin": 10,
"textAlign": "center",
}
}>
Welcome to React Native!
</Text>
<Text
style={
Object {
"color": "#333333",
"marginBottom": 5,
"textAlign": "center",
}
}>
This is a React Native snapshot test.
</Text>
</View>
`;
下次你运行测试时,渲染的结果将会和之前创建的快照进行比较。 代码变动时,快照也应该被提交。 当快照测试失败,你需要去检查是否是你想要或不想要的变动。 如果变动符合预期,你可以通过jest -u
调用Jest从而重写存在的快照。
The code for this example is available at examples/react-native.