1. Jest 和 React Native 测试库简介
Jest 是由 Facebook 维护的 JavaScript 测试框架。因其易用性、全面的功能以及与各种 JavaScript 库的集成而被广泛使用。
React Native 测试库(RNTL) 是一个为测试 React Native 组件提供简单且完整实用工具的库。受 React 测试库的启发,它专注于模拟用户与应用程序交互方式的测试。
2. 安装和配置
React Native CLI 的配置
安装:
要安装 Jest 和 React Native 测试库,可以使用 npm 或 yarn:
npm install --save-dev jest @testing-library/react-native # 或者 yarn add --dev jest @testing-library/react-native
配置:
在项目的根目录创建或编辑 jest.config.js
文件来配置 Jest:
module.exports = { preset: 'eact-native', setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'], transformIgnorePatterns: [ 'node_modules/(?!(jest-)?react-native|@react-native|@react-native-community|@testing-library)', ], testPathIgnorePatterns: ['/node_modules/', '/android/', '/ios/'], };
Expo 的配置
安装:
对于 Expo 项目,使用以下命令安装必要的依赖项:
expo install jest @testing-library/react-native @testing-library/jest-native
配置:
在项目的根目录创建或编辑 jest.config.js
文件,专门为 Expo 项目配置 Jest:
module.exports = { preset: 'jest-expo', setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'], transformIgnorePatterns: [ 'node_modules/(?!(jest-)?react-native|@react-native|@react-native-community|@expo|expo(nent)?|@unimodules)', ], testPathIgnorePatterns: ['/node_modules/', '/android/', '/ios/'], };
Expo 托管工作流的额外配置:
对于使用 Expo 托管工作流的项目,在 package.json
中添加以下脚本以确保 Jest 正常工作:
"scripts": { "test": "jest" }
3. 最常用的方法和实用工具
渲染:
-
render
:渲染用于测试的组件。
import { render } from '@testing-library/react-native'; import MyComponent from '../MyComponent'; test('renders correctly', () => { const { getByText } = render(<MyComponent />); expect(getByText('Hello World')).toBeTruthy(); });
查询:
-
getByText
:通过文本查找元素。 -
getByTestId
:通过testID
查找元素。
const { getByTestId } = render(<MyComponent />); expect(getByTestId('uniqueId')).toBeTruthy();
操作:
-
fireEvent
:模拟用户事件,如press
(点击)、changeText
(更改文本)等。
import { fireEvent } from '@testing-library/react-native'; test('button press', () => { const { getByText } = render(<MyComponent />); fireEvent.press(getByText('Press me')); expect(someMockFunction).toHaveBeenCalled(); });
4. 编写测试
渲染测试:
test('renders correctly', () => { const { getByText } = render(<MyComponent />); expect(getByText('Hello World')).toBeTruthy(); });
交互测试:
test('button press changes text', () => { const { getByText, getByTestId } = render(<MyComponent />); fireEvent.press(getByText('Press me')); expect(getByTestId('textId').props.children).toBe('Button Pressed'); });
属性测试:
test('renders with correct props', () => { const { getByText } = render(<MyComponent title="Test Title" />); expect(getByText('Test Title')).toBeTruthy(); });
5. 用例示例
带有 API 调用的组件测试:
对于进行 API 调用的组件,可以使用 jest.mock
来模拟 API 响应。
import axios from 'axios'; import MyComponent from '../MyComponent'; jest.mock('axios'); test('fetches and displays data', async () => { axios.get.mockResolvedValueOnce({ data: { title: 'Mock Title' } }); const { findByText } = render(<MyComponent />); expect(await findByText('Mock Title')).toBeTruthy(); });
导航测试:
要测试导航,可以使用 react-navigation
及其模拟功能。
import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import MyComponent from '../MyComponent'; import { render } from '@testing-library/react-native'; const Stack = createStackNavigator(); test('navigates correctly', () => { const component = ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={MyComponent} /> </Stack.Navigator> </NavigationContainer> ); const { getByText } = render(component); expect(getByText('Home')).toBeTruthy(); });
Jest 和 React Native 测试库是强大的工具,可确保您的 React Native 代码的质量。通过单元测试和集成测试,您可以在错误到达最终用户之前捕获它们,提高应用程序的可靠性。