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

使用react-hooks-testing-library测试自定义Hook时result.current未更新如何解决

问题原因及解决方法

1. 核心错误:renderHook 回调未返回Hook执行结果

renderHook的回调函数需要将目标Hook的返回值return出去,才能通过result.current拿到Hook的实时返回值。你的代码里只调用了useImageSize没有返回,所以即使Hook内部状态更新,测试侧也拿不到结果。
修改对应代码:

// 修改前
const { result } = renderHook(() => {
  useImageSize('test_image', true, false)
});

// 修改后
const { result } = renderHook(() => {
  return useImageSize('test_image', true, false)
});
// 简写形式
const { result } = renderHook(() => useImageSize('test_image', true, false));

2. 次要问题:测试代码语法错误

你贴出的测试代码存在冗余语法,it块结束后多了半段重复的console和expect逻辑,还有多余的闭合括号,直接删除这部分冗余代码即可,否则测试无法正常执行。

3. 可选优化:屏蔽LayoutAnimation的副作用

如果测试过程中报LayoutAnimation相关警告,可以在测试开头加对应模拟:

jest.spyOn(RN.LayoutAnimation, 'easeInEaseOut').mockImplementation(jest.fn());

修改后的完整测试代码

import * as RN from 'react-native';
import { renderHook, act } from '@testing-library/react-hooks';
import { useImageSize } from '@app/hooks/useImageSize';

describe('useImageSize', () => {
  const getSizeSpyOn = jest.spyOn(RN.Image, 'getSize').mockImplementation(jest.fn());
  // 可选:屏蔽LayoutAnimation的副作用
  jest.spyOn(RN.LayoutAnimation, 'easeInEaseOut').mockImplementation(jest.fn());

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should return the correct size when we want to fill the width of the screen', () => {
    jest.spyOn(RN, 'useWindowDimensions').mockReturnValue({ width: 200, height: 200, fontScale: 1, scale: 1 });
    // 修正了返回逻辑
    const { result } = renderHook(() => useImageSize('test_image', true, false));

    expect(getSizeSpyOn).toHaveBeenCalledTimes(1)

    const getSizeArgs = getSizeSpyOn.mock.calls[0]!;
    expect(getSizeArgs[0]).toBe('test_image');

    const success = getSizeArgs[1];

    act(() => {
      success(100, 50);
    });

    console.log('result.current', result.current)

    expect(result.current).toEqual({
      width: 200,
      height: 100,
    });
  });
});

修改完成后重新运行测试,result.current就能正常获取到更新后的状态值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:42:04