Тестирование React Native приложений
At Facebook, we use Jest to test React Native applications.
Get a deeper insight into testing a working React Native app example by reading the following series: Part 1: Jest – Snapshot come into play and Part 2: Jest – Redux Snapshots for your Actions and Reducers.
Настройка
Начиная с react-native версии 0.38, по умолчанию, установка Jest выполняется при выполнении команды react-native init
. Следующая конфигурация должна быть автоматически добавлена в ваш файл package.json:
{
"scripts": {
"test": "jest"
},
"jest": {
"preset": "react-native"
}
}
Run yarn test
to run tests with 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.
Тестирование при помощи снимков
Let's create a snapshot test for a small intro component with a few views and text components and some styles:
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 и функции создания снимков 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();
});
When you run yarn test
or jest
, this will produce an output file like this:
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 командой jest -u
для перезаписи существующих снимков.
The code for this example is available at examples/react-native.
Preset configuration
The preset sets up the environment and is very opinionated and based on what we found to be useful at Facebook. All of the configuration options can be overwritten just as they can be customized when no preset is used.