《Jest 与 React Native 测试库结合的力量》

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 代码的质量。通过单元测试和集成测试,您可以在错误到达最终用户之前捕获它们,提高应用程序的可靠性。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幻想多巴胺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值