You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对使用react-native-modalize的React Native组件进行单元测试

react-native-modalize 组件单元测试方案

前置依赖

默认使用 Jest + @testing-library/react-native 作为测试工具栈,未安装的话可先完成依赖安装。

测试实现步骤

1. 模拟第三方组件

我们不需要测试 react-native-modalize 本身的功能,所以直接模拟组件及其暴露的方法即可,在测试文件顶部添加如下模拟代码:

jest.mock('react-native-modalize', () => {
  // 模拟open方法
  export const mockOpen = jest.fn();
  const Modalize = jest.fn(({ children, ref }) => {
    // 给ref绑定模拟的实例方法
    if (ref) {
      ref.current = { open: mockOpen };
    }
    // 直接返回子元素,方便测试子内容渲染
    return children;
  });
  return { Modalize, mockOpen };
});

2. 编写测试用例

完整测试代码如下:

import React from 'react';
import { render, screen } from '@testing-library/react-native';
import { mockOpen, Modalize } from 'react-native-modalize';
import TestComponent from './TestComponent'; // 替换为你的组件实际路径

// 用例1:验证组件挂载后自动调用open方法
test('组件挂载时触发Modalize打开', () => {
  render(<TestComponent />);
  expect(mockOpen).toHaveBeenCalledTimes(1);
});

// 用例2:验证Modalize接收的props符合预期
test('Modalize接收到正确的alwaysOpen参数', () => {
  render(<TestComponent />);
  expect(Modalize).toHaveBeenCalledWith(
    expect.objectContaining({
      alwaysOpen: 400
    }),
    expect.anything()
  );
});

// 用例3:验证Modalize内的子内容正常渲染
test('Modalize子内容渲染正常', () => {
  render(<TestComponent />);
  expect(screen.getByText('Hello')).toBeTruthy();
});

注意事项

  • 若存在关闭、调整高度等其他交互逻辑,可在模拟组件时新增对应方法,验证调用时机、参数即可
  • 异步场景下可替换getByText为findByText适配渲染等待逻辑
  • 测试仅覆盖自身业务逻辑即可,第三方组件的原生功能无需额外测试

内容的提问来源于stack exchange,提问作者Bauyrzhan Matyganov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:18:02