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

如何在React Testing Library中更新Context值触发useEffect执行?

测试依赖Context的组件useEffect触发方案

问题1:更新Context中的date值

使用@testing-library/react的render方法返回的rerender函数,重新渲染包裹了Context Provider的组件,传入新的Context值即可触发上下文更新,进而触发组件的依赖变化检测。

问题2:验证useEffect是否正确调用

不需要单独监听useEffect的执行,你只需要验证useEffect内的副作用函数(即本次测试的scrollIntoView)是否按预期触发即可,副作用执行即代表useEffect被正确调用。


完整可运行测试代码

it('should scroll into AnotherComponent when date is updated', () => {
  const mockScrollIntoView = jest.fn();
  window.HTMLElement.prototype.scrollIntoView = mockScrollIntoView;

  // 首次渲染,传入初始date值
  const { rerender } = render(
    <MyContext.Provider value={{ date: '2021-11-01' }}>
      <MyComponent />
    </MyContext.Provider>
  );

  // 清空首次渲染可能产生的调用记录,避免干扰后续断言
  mockScrollIntoView.mockClear();

  // 重新渲染,传入新的date值触发Context更新
  rerender(
    <MyContext.Provider value={{ date: '2021-11-02' }}>
      <MyComponent />
    </MyContext.Provider>
  );

  // 断言scrollIntoView被调用,说明useEffect按预期执行
  expect(mockScrollIntoView).toHaveBeenCalledTimes(1);
});

注意事项

如果你的AnotherComponent没有做ref转发,ref.current会返回undefined,导致scrollIntoView不会被触发,需要给AnotherComponent加上forwardRef包裹:

// AnotherComponent.tsx 示例
import { forwardRef } from 'react';

export const AnotherComponent = forwardRef<HTMLDivElement>((props, ref) => {
  return <div ref={ref}>{/* 组件原有逻辑 */}</div>
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:04