测试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:

  1. {
  2. "scripts": {
  3. "test": "jest"
  4. },
  5. "jest": {
  6. "preset": "react-native"
  7. }
  8. }

Note: 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.

yarn test 来运行 Jest 测试。

Snapshot Test

下面来为一个入门的小型组件创建一个快照测试,它的内部有些View、Text组件和一些样式:

Intro.js

  1. import React, {Component} from 'react';
  2. import {StyleSheet, Text, View} from 'react-native';
  3. class Intro extends Component {
  4. render() {
  5. return (
  6. <View style={styles.container}>
  7. <Text style={styles.welcome}>Welcome to React Native!</Text>
  8. <Text style={styles.instructions}>
  9. This is a React Native snapshot test.
  10. </Text>
  11. </View>
  12. );
  13. }
  14. }
  15. const styles = StyleSheet.create({
  16. container: {
  17. alignItems: 'center',
  18. backgroundColor: '#F5FCFF',
  19. flex: 1,
  20. justifyContent: 'center',
  21. },
  22. instructions: {
  23. color: '#333333',
  24. marginBottom: 5,
  25. textAlign: 'center',
  26. },
  27. welcome: {
  28. fontSize: 20,
  29. margin: 10,
  30. textAlign: 'center',
  31. },
  32. });
  33. export default Intro;

现在,使用React的test renderer和Jest的快照特性来和组件交互,获得渲染结果和生成快照文件:

__tests__/Intro-test.js

  1. import React from 'react';
  2. import renderer from 'react-test-renderer';
  3. import Intro from '../Intro';
  4. test('renders correctly', () => {
  5. const tree = renderer.create(<Intro />).toJSON();
  6. expect(tree).toMatchSnapshot();
  7. });

当你运行 npm test 或者 jest,将产生一个像下面的文件:

__tests__/__snapshots__/Intro-test.js.snap

  1. exports[`Intro renders correctly 1`] = `
  2. <View
  3. style={
  4. Object {
  5. "alignItems": "center",
  6. "backgroundColor": "#F5FCFF",
  7. "flex": 1,
  8. "justifyContent": "center",
  9. }
  10. }>
  11. <Text
  12. style={
  13. Object {
  14. "fontSize": 20,
  15. "margin": 10,
  16. "textAlign": "center",
  17. }
  18. }>
  19. Welcome to React Native!
  20. </Text>
  21. <Text
  22. style={
  23. Object {
  24. "color": "#333333",
  25. "marginBottom": 5,
  26. "textAlign": "center",
  27. }
  28. }>
  29. This is a React Native snapshot test.
  30. </Text>
  31. </View>
  32. `;

下次你运行测试时,渲染的结果将会和之前创建的快照进行比较。 代码变动时,快照也应该被提交。 当快照测试失败,你需要去检查是否是你想要或不想要的变动。 如果变动符合预期,你可以通过jest -u调用Jest从而重写存在的快照。

The code for this example is available at examples/react-native.

预设配置

Preset是基于我们在Facebook的经验生成的一套基本配置,并且可自定义覆盖。 所有的配置项都可以被重写。

环境

react-native ships with a Jest preset, so the jest.preset field of your package.json should point to react-native. The preset is a node environment that mimics the environment of a React Native app. Because it doesn’t load any DOM or browser APIs, it greatly improves Jest’s startup time. The preset is a node environment that mimics the environment of a React Native app. Because it doesn’t load any DOM or browser APIs, it greatly improves Jest’s startup time.

transformIgnorePatterns customization

The transformIgnorePatterns option can be used to specify which files shall be transformed by Babel. Many react-native npm modules unfortunately don’t pre-compile their source code before publishing. Many react-native npm modules unfortunately don’t pre-compile their source code before publishing.

By default the jest-react-native preset only processes the project’s own source files and react-native. If you have npm dependencies that have to be transformed you can customize this configuration option by including modules other than react-native by grouping them and separating them with the | operator:

  1. {
  2. "transformIgnorePatterns": [
  3. "node_modules/(?!(react-native|my-project|react-native-button)/)"
  4. ]
  5. }

You can test which paths would match (and thus be excluded from transformation) with a tool like this.

transformIgnorePatterns will exclude a file from transformation if the path matches against any pattern provided. Splitting into multiple patterns could therefore have unintended results if you are not careful. In the example below, the exclusion (also known as a negative lookahead assertion) for foo and bar cancel each other out:

  1. {
  2. "transformIgnorePatterns": ["node_modules/(?!foo/)", "node_modules/(?!bar/)"] // not what you want
  3. }

setupFiles

If you’d like to provide additional configuration for every test file, the setupFiles configuration option can be used to specify setup scripts.

moduleNameMapper

可以使用 modulenamemapper 将模块路径映射到其他模块。 By default the preset maps all images to an image stub module but if a module cannot be found this configuration option can help:

  1. {
  2. "moduleNameMapper": {
  3. "my-module.js": "<rootDir>/path/to/my-module.js"
  4. }
  5. }

Tips

Mock native modules using jest.mock

The Jest preset built into react-native comes with a few default mocks that are applied on a react-native repository. However, some react-native components or third party components rely on native code to be rendered. In such cases, Jest’s manual mocking system can help to mock out the underlying implementation. However, some react-native components or third party components rely on native code to be rendered. In such cases, Jest’s manual mocking system can help to mock out the underlying implementation.

For example, if your code depends on a third party native video component called react-native-video you might want to stub it out with a manual mock like this:

  1. jest.mock('react-native-video', () => 'Video');

This will render the component as <Video {...props} /> with all of its props in the snapshot output. 想了解更多还可以阅读 caveats around Enzyme and React 16. 想了解更多还可以阅读 caveats around Enzyme and React 16.

Sometimes you need to provide a more complex manual mock. Sometimes you need to provide a more complex manual mock. For example if you’d like to forward the prop types or static fields of a native component to a mock, you can return a different React component from a mock through this helper from jest-react-native:

  1. jest.mock('path/to/MyNativeComponent', () => {
  2. const mockComponent = require('react-native/jest/mockComponent');
  3. return mockComponent('path/to/MyNativeComponent');
  4. });

Or if you’d like to create your own manual mock, you can do something like this:

  1. jest.mock('Text', () => {
  2. const RealComponent = jest.requireActual('Text');
  3. const React = require('react');
  4. class Text extends React.Component {
  5. render() {
  6. return React.createElement('Text', this.props, this.props.children);
  7. }
  8. }
  9. Text.propTypes = RealComponent.propTypes;
  10. return Text;
  11. });

In other cases you may want to mock a native module that isn’t a React component. The same technique can be applied. We recommend inspecting the native module’s source code and logging the module when running a react native app on a real device and then modeling a manual mock after the real module. The same technique can be applied. We recommend inspecting the native module’s source code and logging the module when running a react native app on a real device and then modeling a manual mock after the real module.

If you end up mocking the same modules over and over it is recommended to define these mocks in a separate file and add it to the list of setupFiles.