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

React-test-renderer测试报错:无法读取undefined的'current'属性

排查并解决React Native测试中TypeError: Cannot read properties of undefined (reading 'current')问题

核心原因分析

报错指向ref.current未定义,说明测试环境中某个React ref未被正确初始化或挂载。组件实际运行正常是因为生产环境中组件挂载流程完整,ref能被正确赋值,但测试环境下可能存在组件未完全挂载、依赖组件未被正确模拟,或者代码中未对ref的存在性做判断的情况。

具体排查与修复步骤

1. 定位报错的ref来源

首先查看测试报错的栈跟踪信息,找到具体是哪个ref的current属性触发了错误。可能的来源包括:

  • WarrantyToggle组件自身定义的useRef
  • 依赖的iconAnimation组件内部的ref
  • 依赖的Form组件内部的ref

2. 给ref的使用添加安全判断

如果是组件代码中直接调用ref.current而未做存在性检查,修改代码添加可选链操作符:

// 原代码(可能报错)
iconRef.current.startAnimation();

// 修改后
iconRef.current?.startAnimation();

这种修改既能兼容测试环境,也能提升生产代码的健壮性。

3. 确保测试中组件完全挂载

react-test-renderer的同步渲染可能导致ref还未被赋值就执行了断言,改用异步等待确保组件挂载完成:

import renderer from 'react-test-renderer';
import { waitFor } from '@testing-library/react-native';
import WarrantyToggle from '../WarrantyToggle';

test('WarrantyToggle renders correctly', async () => {
  const component = renderer.create(<WarrantyToggle />);
  await waitFor(() => {
    expect(component.toJSON()).toMatchSnapshot();
  });
});

4. 正确模拟依赖组件的ref

如果报错来自iconAnimation或Form组件内部的ref,需要在测试中mock这些组件并正确处理ref传递:

  • 模拟iconAnimation组件示例:
import React from 'react';
import { View } from 'react-native';
import renderer from 'react-test-renderer';
import WarrantyToggle from '../WarrantyToggle';

// Mock iconAnimation组件,处理ref暴露必要方法
jest.mock('../path/to/iconAnimation', () => {
  const MockIcon = React.forwardRef((props, ref) => {
    React.useImperativeHandle(ref, () => ({
      startAnimation: jest.fn(),
      stopAnimation: jest.fn()
    }));
    return <View {...props} />;
  });
  return MockIcon;
});

test('WarrantyToggle interacts correctly', () => {
  const component = renderer.create(<WarrantyToggle />);
  // 执行测试逻辑
});

5. 检查依赖版本兼容性

确保react-test-renderer的版本与项目中react、react-native的版本完全匹配,版本不兼容可能导致ref挂载异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:10:28