You need to enable JavaScript to run this app. 如何使用React Testing Library测试react-lazyload懒加载组件是否存在
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Testing Library测试react-lazyload懒加载组件是否存在

问题原因
  • react-lazyload 内部通过元素的 getBoundingClientRect 返回值判断是否进入视口,仅修改 window.scrollY 不会自动更新 jsdom 环境中元素的位置计算结果,导致懒加载逻辑判定元素仍未出现在视口范围
  • react-lazyload 的滚动回调默认配置了300ms的防抖逻辑,触发滚动后直接断言没有等待回调执行,组件还未触发懒加载渲染
  • 部分版本的 react-lazyload 会自动识别滚动容器,若识别错误会导致没有监听 window 的滚动事件,触发的滚动事件无法被组件捕获
修复步骤
  1. 模拟元素初始位置,让懒加载逻辑可以正确识别元素位置:
// 测试前置钩子中模拟元素位置计算方法
beforeEach(() => {
  // 初始状态元素在视口下方1600px位置
  Element.prototype.getBoundingClientRect = jest.fn(() => ({
    top: 1600,
    bottom: 2000,
    left: 0,
    right: 375,
    width: 375,
    height: 400,
  }))
  // 启用假定时器跳过防抖等待
  jest.useFakeTimers()
})

// 测试后置钩子恢复原生方法
afterEach(() => {
  jest.useRealTimers()
  jest.restoreAllMocks()
})
  1. 修正测试用例逻辑,触发滚动后快进防抖时间:
it('should show images on scroll', async () => {
  renderComponent(defaultProps);
  // 先校验初始状态图片未加载
  expect(screen.queryByAltText('product-showcase')).not.toBeInTheDocument();

  // 触发window滚动
  fireEvent.scroll(window, { target: { scrollY: 1500 } });
  // 快进所有定时器,跳过react-lazyload的防抖等待
  jest.runAllTimers();

  // 等待组件更新后断言图片可见
  expect(await screen.findByAltText('product-showcase')).toBeVisible();
});
  1. 如果修改后仍然失败,可以给LazyLoad组件添加overflow={false}属性,强制组件监听window滚动事件:
<LazyLoad offset={950} overflow={false}>
  <ImageWrapper>
    <picture>
      <source type="image/webp" srcSet={heroImageWebp} />
      <source type="image/png" srcSet={heroImagePng} />
      <img src={heroImagePng} alt={'product-showcase'} />
    </picture>
    <AnimationWrapper>
      <MobileReaderAnimation
        animate={mobileReaderAnimationVisibility}
        initial={'hidden'}
        animations={animationsEnabled}
      />
    </AnimationWrapper>
  </ImageWrapper>
</LazyLoad>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 11:42:01